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