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