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