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