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