]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_Document.cpp
Salome HOME
e583a0fb8b1698aa71045bad491113ae302ebbff
[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, const std::string theKind)
49     : myID(theID), myKind(theKind),
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     // to avoid the problem that feature is created in the current, not this, document
150     Model_Session::get()->setActiveDocument(anApp->getDocument(myID));
151     synchronizeFeatures();
152   }
153   return !isError;
154 }
155
156 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
157 {
158   // create a directory in the root document if it is not yet exist
159   if (this == Model_Session::get()->moduleDocument().get()) {
160 #ifdef WIN32
161     CreateDirectory(theFileName, NULL);
162 #else
163     mkdir(theFileName, 0x1ff);
164 #endif
165   }
166   // filename in the dir is id of document inside of the given directory
167   TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
168   PCDM_StoreStatus aStatus;
169   try {
170     aStatus = Model_Application::getApplication()->SaveAs(myDoc, aPath);
171   } catch (Standard_Failure) {
172     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
173     Events_Error::send(
174         std::string("Exception in saving of document: ") + aFail->GetMessageString());
175     return false;
176   }
177   bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
178   if (!isDone) {
179     switch (aStatus) {
180       case PCDM_SS_DriverFailure:
181         Events_Error::send(std::string("Can not save document: save driver-library failure"));
182         break;
183       case PCDM_SS_WriteFailure:
184         Events_Error::send(std::string("Can not save document: file writing failure"));
185         break;
186       case PCDM_SS_Failure:
187       default:
188         Events_Error::send(std::string("Can not save document"));
189         break;
190     }
191   }
192   myTransactionsAfterSave = 0;
193   if (isDone) {  // save also sub-documents if any
194     theResults.push_back(TCollection_AsciiString(aPath).ToCString());
195     std::set<std::string>::iterator aSubIter = mySubs.begin();
196     for (; aSubIter != mySubs.end() && isDone; aSubIter++) {
197       isDone = subDoc(*aSubIter)->save(theFileName, theResults);
198     }
199   }
200   return isDone;
201 }
202
203 void Model_Document::close()
204 {
205   boost::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
206   if (this != aPM->moduleDocument().get() && this == aPM->activeDocument().get()) {
207     aPM->setActiveDocument(aPM->moduleDocument());
208   }
209   // close all subs
210   std::set<std::string>::iterator aSubIter = mySubs.begin();
211   for (; aSubIter != mySubs.end(); aSubIter++)
212     subDoc(*aSubIter)->close();
213   mySubs.clear();
214   // close this
215   /* do not close because it can be undoed
216    if (myDoc->CanClose() == CDM_CCS_OK)
217    myDoc->Close();
218    Model_Application::getApplication()->deleteDocument(myID);
219    */
220 }
221
222 void Model_Document::startOperation()
223 {
224   if (myDoc->HasOpenCommand()) {  // start of nested command
225     if (myNestedNum == -1) {
226       myNestedNum = 0;
227       myDoc->InitDeltaCompaction();
228     }
229     myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand();
230     myTransactionsAfterSave++;
231     myDoc->OpenCommand();
232   } else {  // start the simple command
233     myDoc->NewCommand();
234   }
235   // new command for all subs
236   std::set<std::string>::iterator aSubIter = mySubs.begin();
237   for (; aSubIter != mySubs.end(); aSubIter++)
238     subDoc(*aSubIter)->startOperation();
239 }
240
241 bool Model_Document::compactNested()
242 {
243   bool allWasEmpty = true;
244   while (myNestedNum != -1) {
245     myTransactionsAfterSave--;
246     if (!myIsEmptyTr[myTransactionsAfterSave]) {
247       allWasEmpty = false;
248     }
249     myIsEmptyTr.erase(myTransactionsAfterSave);
250     myNestedNum--;
251   }
252   myIsEmptyTr[myTransactionsAfterSave] = allWasEmpty;
253   myTransactionsAfterSave++;
254   myDoc->PerformDeltaCompaction();
255   return !allWasEmpty;
256 }
257
258 void Model_Document::finishOperation()
259 {
260   // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
261   std::set<std::string>::iterator aSubIter = mySubs.begin();
262   for (; aSubIter != mySubs.end(); aSubIter++)
263     subDoc(*aSubIter)->finishOperation();
264
265   // just to be sure that everybody knows that changes were performed
266   if (!myDoc->HasOpenCommand() && myNestedNum != -1)
267     boost::static_pointer_cast<Model_Session>(Model_Session::get())
268         ->setCheckTransactions(false);  // for nested transaction commit
269   Events_Loop* aLoop = Events_Loop::loop();
270   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
271   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
272   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
273   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
274   if (!myDoc->HasOpenCommand() && myNestedNum != -1)
275     boost::static_pointer_cast<Model_Session>(Model_Session::get())
276         ->setCheckTransactions(true);  // for nested transaction commit
277
278   if (myNestedNum != -1)  // this nested transaction is owervritten
279     myNestedNum++;
280   if (!myDoc->HasOpenCommand()) {
281     if (myNestedNum != -1) {
282       myNestedNum--;
283       compactNested();
284     }
285   } else {
286     // returns false if delta is empty and no transaction was made
287     myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand();  // && (myNestedNum == -1);
288     myTransactionsAfterSave++;
289   }
290
291 }
292
293 void Model_Document::abortOperation()
294 {
295   if (myNestedNum > 0 && !myDoc->HasOpenCommand()) {  // abort all what was done in nested
296       // first compact all nested
297     if (compactNested()) {
298       // for nested it is undo and clear redos
299       myDoc->Undo();
300     }
301     myDoc->ClearRedos();
302     myTransactionsAfterSave--;
303     myIsEmptyTr.erase(myTransactionsAfterSave);
304   } else {
305     if (myNestedNum == 0)  // abort only high-level
306       myNestedNum = -1;
307     myDoc->AbortCommand();
308   }
309   synchronizeFeatures(true);
310   // abort for all subs
311   std::set<std::string>::iterator aSubIter = mySubs.begin();
312   for (; aSubIter != mySubs.end(); aSubIter++)
313     subDoc(*aSubIter)->abortOperation();
314 }
315
316 bool Model_Document::isOperation()
317 {
318   // operation is opened for all documents: no need to check subs
319   return myDoc->HasOpenCommand() == Standard_True ;
320 }
321
322 bool Model_Document::isModified()
323 {
324   // is modified if at least one operation was commited and not undoed
325   return myTransactionsAfterSave > 0 || isOperation();
326 }
327
328 bool Model_Document::canUndo()
329 {
330   if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0
331       && myTransactionsAfterSave != 0 /* for omitting the first useless transaction */)
332     return true;
333   // check other subs contains operation that can be undoed
334   std::set<std::string>::iterator aSubIter = mySubs.begin();
335   for (; aSubIter != mySubs.end(); aSubIter++)
336     if (subDoc(*aSubIter)->canUndo())
337       return true;
338   return false;
339 }
340
341 void Model_Document::undo()
342 {
343   myTransactionsAfterSave--;
344   if (myNestedNum > 0)
345     myNestedNum--;
346   if (!myIsEmptyTr[myTransactionsAfterSave])
347     myDoc->Undo();
348   synchronizeFeatures(true);
349   // undo for all subs
350   std::set<std::string>::iterator aSubIter = mySubs.begin();
351   for (; aSubIter != mySubs.end(); aSubIter++)
352     subDoc(*aSubIter)->undo();
353 }
354
355 bool Model_Document::canRedo()
356 {
357   if (myDoc->GetAvailableRedos() > 0)
358     return true;
359   // check other subs contains operation that can be redoed
360   std::set<std::string>::iterator aSubIter = mySubs.begin();
361   for (; aSubIter != mySubs.end(); aSubIter++)
362     if (subDoc(*aSubIter)->canRedo())
363       return true;
364   return false;
365 }
366
367 void Model_Document::redo()
368 {
369   if (myNestedNum != -1)
370     myNestedNum++;
371   if (!myIsEmptyTr[myTransactionsAfterSave])
372     myDoc->Redo();
373   myTransactionsAfterSave++;
374   synchronizeFeatures(true);
375   // redo for all subs
376   std::set<std::string>::iterator aSubIter = mySubs.begin();
377   for (; aSubIter != mySubs.end(); aSubIter++)
378     subDoc(*aSubIter)->redo();
379 }
380
381 /// Appenad to the array of references a new referenced label
382 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
383 {
384   Handle(TDataStd_ReferenceArray) aRefs;
385   if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
386     aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
387     aRefs->SetValue(0, theReferenced);
388   } else {  // extend array by one more element
389     Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
390                                                                         aRefs->Upper() + 1);
391     for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
392       aNewArray->SetValue(a, aRefs->Value(a));
393     }
394     aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
395     aRefs->SetInternalArray(aNewArray);
396   }
397 }
398
399 FeaturePtr Model_Document::addFeature(std::string theID)
400 {
401   TDF_Label anEmptyLab;
402   FeaturePtr anEmptyFeature;
403   FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
404   if (!aFeature)
405     return aFeature;
406   boost::shared_ptr<Model_Document> aDocToAdd = boost::dynamic_pointer_cast<Model_Document>(
407       aFeature->documentToAdd());
408   if (aFeature) {
409     TDF_Label aFeatureLab;
410     if (!aFeature->isAction()) {  // do not add action to the data model
411       TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
412       aFeatureLab = aFeaturesLab.NewChild();
413       aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
414       // keep the feature ID to restore document later correctly
415       TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
416       aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
417       // store feature in the history of features array
418       if (aFeature->isInHistory()) {
419         AddToRefArray(aFeaturesLab, aFeatureLab);
420       }
421     }
422     if (!aFeature->isAction()) {  // do not add action to the data model
423       // event: feature is added
424       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
425       ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
426     } else { // feature must be executed
427        // no creation event => updater not working, problem with remove part
428       aFeature->execute();
429     }
430   }
431   return aFeature;
432 }
433
434 /// Appenad to the array of references a new referenced label.
435 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
436 /// \returns the index of removed element
437 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
438                                   -1)
439 {
440   int aResult = -1;  // no returned
441   Handle(TDataStd_ReferenceArray) aRefs;
442   if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
443     if (aRefs->Length() == 1) {  // just erase an array
444       if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
445         theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
446       }
447       aResult = 0;
448     } else {  // reduce the array
449       Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
450                                                                           aRefs->Upper() - 1);
451       int aCount = aRefs->Lower();
452       for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
453         if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
454           aCount--;
455           aResult = a;
456         } else {
457           aNewArray->SetValue(aCount, aRefs->Value(a));
458         }
459       }
460       aRefs->SetInternalArray(aNewArray);
461     }
462   }
463   return aResult;
464 }
465
466 void Model_Document::removeFeature(FeaturePtr theFeature, const bool theCheck)
467 {
468   if (theCheck) {
469     // check the feature: it must have no depended objects on it
470     std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
471     for(; aResIter != theFeature->results().cend(); aResIter++) {
472       if (myConcealedResults.find(*aResIter) != myConcealedResults.end()) {
473         Events_Error::send("Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
474         return;
475       }
476     }
477     NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myObjs);
478     for(; anObjIter.More(); anObjIter.Next()) {
479       DataPtr aData = anObjIter.Value()->data();
480       if (aData->referencesTo(theFeature)) {
481         Events_Error::send("Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
482         return;
483       }
484     }
485   }
486
487   boost::shared_ptr<Model_Data> aData = boost::static_pointer_cast<Model_Data>(theFeature->data());
488   TDF_Label aFeatureLabel = aData->label().Father();
489   if (myObjs.IsBound(aFeatureLabel))
490     myObjs.UnBind(aFeatureLabel);
491   else
492     return;  // not found feature => do not remove
493   // erase fields
494   theFeature->erase();
495   // erase all attributes under the label of feature
496   aFeatureLabel.ForgetAllAttributes();
497   // remove it from the references array
498   RemoveFromRefArray(featuresLabel(), aFeatureLabel);
499
500   // event: feature is deleted
501   ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
502   /* this is in "erase"
503   // results of this feature must be redisplayed
504   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
505   const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
506   std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
507   for (; aRIter != aResults.cend(); aRIter++) {
508     boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
509     aRes->setData(boost::shared_ptr<ModelAPI_Data>());  // deleted flag
510     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
511     ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), aRes->groupName());
512   }
513   */
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;
596         if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
597           isIn = myConcealedResults.find(*aRIter) == myConcealedResults.end();
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 = myConcealedResults.find(*aRIter) == myConcealedResults.end();
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->isInHistory() && 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)->isInHistory() && (*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)
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     if (!myObjs.IsBound(aFeatureLabel)) {  // a new feature is inserted
722       // create a feature
723       FeaturePtr aNewObj = ModelAPI_Session::get()->createFeature(
724           TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
725               .ToCString());
726       if (!aNewObj) {  // somethig is wrong, most probably, the opened document has invalid structure
727         Events_Error::send("Invalid type of object in the document");
728         aLabIter.Value()->Label().ForgetAllAttributes();
729         continue;
730       }
731       // this must be before "setData" to redo the sketch line correctly
732       myObjs.Bind(aFeatureLabel, aNewObj);
733       aNewFeatures.insert(aNewObj);
734       initData(aNewObj, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
735
736       // event: model is updated
737       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
738       ModelAPI_EventCreator::get()->sendUpdated(aNewObj, anEvent);
739
740       // update results of the appeared feature
741       updateResults(aNewObj);
742     } else {  // nothing is changed, both iterators are incremented
743       FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
744       aKeptFeatures.insert(aFeature);
745       if (theMarkUpdated) {
746         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
747         ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
748       }
749       updateResults(aFeature);
750     }
751   }
752   // execute new features to restore results: after features creation to make all references valid
753   /*std::set<FeaturePtr>::iterator aNewIter = aNewFeatures.begin();
754    for(; aNewIter != aNewFeatures.end(); aNewIter++) {
755    (*aNewIter)->execute();
756    }*/
757   // check all features are checked: if not => it was removed
758   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
759   while (aFIter.More()) {
760     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
761         && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
762       FeaturePtr aFeature = aFIter.Value();
763       // event: model is updated
764       //if (aFeature->isInHistory()) {
765         ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
766       //}
767       // results of this feature must be redisplayed (hided)
768       static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
769       const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
770       std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
771       /*
772       for (; aRIter != aResults.cend(); aRIter++) {
773         boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
774         //aRes->setData(boost::shared_ptr<ModelAPI_Data>()); // deleted flag
775         ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
776         ModelAPI_EventCreator::get()->sendDeleted(aThis, aRes->groupName());
777       }
778       */
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   myExecuteFeatures = false;
791   aLoop->activateFlushes(true);
792
793   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
794   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
795   if (theMarkUpdated) {
796     aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
797   }
798   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
799   boost::static_pointer_cast<Model_Session>(Model_Session::get())
800     ->setCheckTransactions(true);
801   myExecuteFeatures = true;
802 }
803
804 TDF_Label Model_Document::resultLabel(
805   const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex) 
806 {
807   const boost::shared_ptr<Model_Data>& aData = 
808     boost::dynamic_pointer_cast<Model_Data>(theFeatureData);
809   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
810 }
811
812 void Model_Document::storeResult(boost::shared_ptr<ModelAPI_Data> theFeatureData,
813                                  boost::shared_ptr<ModelAPI_Result> theResult,
814                                  const int theResultIndex)
815 {
816   boost::shared_ptr<ModelAPI_Document> aThis = 
817     Model_Application::getApplication()->getDocument(myID);
818   theResult->setDoc(aThis);
819   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
820   if (theResult->data()->name().empty()) {  // if was not initialized, generate event and set a name
821     theResult->data()->setName(theFeatureData->name());
822   }
823 }
824
825 static const Standard_GUID ID_CONSTRUCTION("b59fa408-8ab1-42b8-980c-af5adeebe7e4");
826 static const Standard_GUID ID_BODY("c1148e9a-9b17-4e9c-9160-18e918fd0013");
827 static const Standard_GUID ID_PART("1b3319b9-3e0a-4298-a1dc-3fb5aaf9be59");
828
829 boost::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
830     const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
831 {
832   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
833   TDataStd_UAttribute::Set(aLab, ID_CONSTRUCTION);
834   ObjectPtr anOldObject = object(aLab);
835   boost::shared_ptr<ModelAPI_ResultConstruction> aResult;
836   if (anOldObject) {
837     aResult = boost::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
838   }
839   if (!aResult) {
840     aResult = boost::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
841     storeResult(theFeatureData, aResult, theIndex);
842   }
843   return aResult;
844 }
845
846 boost::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
847     const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
848 {
849   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
850   TDataStd_UAttribute::Set(aLab, ID_BODY);
851   ObjectPtr anOldObject = object(aLab);
852   boost::shared_ptr<ModelAPI_ResultBody> aResult;
853   if (anOldObject) {
854     aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
855   }
856   if (!aResult) {
857     aResult = boost::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
858     storeResult(theFeatureData, aResult, theIndex);
859   }
860   return aResult;
861 }
862
863 boost::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
864     const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
865 {
866   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
867   TDataStd_UAttribute::Set(aLab, ID_PART);
868   ObjectPtr anOldObject = object(aLab);
869   boost::shared_ptr<ModelAPI_ResultPart> aResult;
870   if (anOldObject) {
871     aResult = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
872   }
873   if (!aResult) {
874     aResult = boost::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
875     storeResult(theFeatureData, aResult, theIndex);
876   }
877   return aResult;
878 }
879
880 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
881     const boost::shared_ptr<ModelAPI_Result>& theResult)
882 {
883   boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>(theResult->data());
884   if (aData) {
885     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
886     return feature(aFeatureLab);
887   }
888   return FeaturePtr();
889 }
890
891 void Model_Document::updateResults(FeaturePtr theFeature)
892 {
893   // for not persistent is will be done by parametric updater automatically
894   if (!theFeature->isPersistentResult()) return;
895   // check the existing results and remove them if there is nothing on the label
896   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
897   while(aResIter != theFeature->results().cend()) {
898     ResultBodyPtr aBody = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(*aResIter);
899     if (aBody) {
900       if (!aBody->data()->isValid()) { 
901         // found a disappeared result => remove it
902         theFeature->removeResult(aBody);
903         // start iterate from beginning because iterator is corrupted by removing
904         aResIter = theFeature->results().cbegin();
905         continue;
906       }
907     }
908     aResIter++;
909   }
910   // check that results are presented on all labels
911   int aResSize = theFeature->results().size();
912   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
913   for(; aLabIter.More(); aLabIter.Next()) {
914     // here must be GUID of the feature
915     int aResIndex = aLabIter.Value().Tag() - 1;
916     ResultPtr aNewBody;
917     if (aResSize <= aResIndex) {
918       TDF_Label anArgLab = aLabIter.Value();
919       if (anArgLab.IsAttribute(ID_BODY)) {
920         aNewBody = createBody(theFeature->data(), aResIndex);
921       } else if (anArgLab.IsAttribute(ID_PART)) {
922         aNewBody = createPart(theFeature->data(), aResIndex);
923       } else if (!anArgLab.IsAttribute(ID_CONSTRUCTION) && anArgLab.FindChild(1).HasAttribute()) {
924         Events_Error::send("Unknown type of result is found in the document");
925       }
926       if (aNewBody) {
927         theFeature->setResult(aNewBody, aResIndex);
928       }
929     }
930   }
931 }
932
933 void Model_Document::objectIsReferenced(const ObjectPtr& theObject)
934 {
935   // only bodies are concealed now
936   ResultBodyPtr aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(theObject);
937   if (aResult) {
938     if (myConcealedResults.find(aResult) != myConcealedResults.end()) {
939       Events_Error::send(std::string("The object '") + aResult->data()->name() +
940         "' is already referenced");
941     } else {
942       myConcealedResults.insert(aResult);
943       boost::shared_ptr<ModelAPI_Document> aThis = 
944         Model_Application::getApplication()->getDocument(myID);
945       ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_ResultBody::group());
946
947       static Events_Loop* aLoop = Events_Loop::loop();
948       static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
949       static const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
950       aECreator->sendUpdated(aResult, EVENT_DISP);
951     }
952   }
953 }
954
955 void Model_Document::objectIsNotReferenced(const ObjectPtr& theObject)
956 {
957   // only bodies are concealed now
958   ResultBodyPtr aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(theObject);
959   if (aResult) {
960     std::set<ResultPtr>::iterator aFind = myConcealedResults.find(aResult);
961     if (aFind != myConcealedResults.end()) {
962       ResultPtr aFeature = *aFind;
963       myConcealedResults.erase(aFind);
964       boost::shared_ptr<ModelAPI_Document> aThis = 
965         Model_Application::getApplication()->getDocument(myID);
966       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
967       ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent, false);
968     } else {
969       Events_Error::send(std::string("The object '") + aResult->data()->name() +
970         "' was not referenced '");
971     }
972   }
973 }
974
975 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
976 {
977   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
978
979 }
980 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
981 {
982   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
983 }