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