Salome HOME
Use validators to set import file formats
[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 <Events_Loop.h>
14 #include <Events_Error.h>
15
16 #include <TDataStd_Integer.hxx>
17 #include <TDataStd_Comment.hxx>
18 #include <TDF_ChildIDIterator.hxx>
19 #include <TDataStd_ReferenceArray.hxx>
20 #include <TDataStd_HLabelArray1.hxx>
21 #include <TDataStd_Name.hxx>
22 #include <TDF_Reference.hxx>
23 #include <TDF_ChildIDIterator.hxx>
24 #include <TDF_LabelMapHasher.hxx>
25
26 #include <climits>
27 #ifndef WIN32
28 #include <sys/stat.h>
29 #endif
30
31 #ifdef WIN32
32 # define _separator_ '\\'
33 #else
34 # define _separator_ '/'
35 #endif
36
37 static const int UNDO_LIMIT = 10;  // number of possible undo operations
38
39 static const int TAG_GENERAL = 1;  // general properties tag
40 static const int TAG_OBJECTS = 2;  // tag of the objects sub-tree (features, results)
41 static const int TAG_HISTORY = 3;  // tag of the history sub-tree (python dump)
42
43 // feature sub-labels
44 static const int TAG_FEATURE_ARGUMENTS = 1;  ///< where the arguments are located
45 static const int TAG_FEATURE_RESULTS = 2;  ///< where the results are located
46
47 Model_Document::Model_Document(const std::string theID, const std::string theKind)
48     : myID(theID), myKind(theKind),
49       myDoc(new TDocStd_Document("BinOcaf"))  // binary OCAF format
50 {
51   myDoc->SetUndoLimit(UNDO_LIMIT);  
52   myTransactionsAfterSave = 0;
53   myNestedNum = -1;
54   myExecuteFeatures = true;
55   // to have something in the document and avoid empty doc open/save problem
56   // in transaction for nesting correct working
57   myDoc->NewCommand();
58   TDataStd_Integer::Set(myDoc->Main().Father(), 0);
59   myDoc->CommitCommand();
60 }
61
62 /// Returns the file name of this document by the nameof directory and identifuer of a document
63 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
64 {
65   TCollection_ExtendedString aPath((const Standard_CString) theFileName);
66   // remove end-separators
67   while(aPath.Length() && (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
68     aPath.Remove(aPath.Length());
69   aPath += _separator_;
70   aPath += theID.c_str();
71   aPath += ".cbf";  // standard binary file extension
72   return aPath;
73 }
74
75 bool Model_Document::load(const char* theFileName)
76 {
77   Handle(Model_Application) anApp = Model_Application::getApplication();
78   if (this == Model_Session::get()->moduleDocument().get()) {
79     anApp->setLoadPath(theFileName);
80   }
81   TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
82   PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
83   try {
84     aStatus = anApp->Open(aPath, myDoc);
85   } catch (Standard_Failure) {
86     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
87     Events_Error::send(
88         std::string("Exception in opening of document: ") + aFail->GetMessageString());
89     return false;
90   }
91   bool isError = aStatus != PCDM_RS_OK;
92   if (isError) {
93     switch (aStatus) {
94       case PCDM_RS_UnknownDocument:
95         Events_Error::send(std::string("Can not open document: unknown format"));
96         break;
97       case PCDM_RS_AlreadyRetrieved:
98         Events_Error::send(std::string("Can not open document: already opened"));
99         break;
100       case PCDM_RS_AlreadyRetrievedAndModified:
101         Events_Error::send(
102             std::string("Can not open document: already opened and modified"));
103         break;
104       case PCDM_RS_NoDriver:
105         Events_Error::send(std::string("Can not open document: driver library is not found"));
106         break;
107       case PCDM_RS_UnknownFileDriver:
108         Events_Error::send(std::string("Can not open document: unknown driver for opening"));
109         break;
110       case PCDM_RS_OpenError:
111         Events_Error::send(std::string("Can not open document: file open error"));
112         break;
113       case PCDM_RS_NoVersion:
114         Events_Error::send(std::string("Can not open document: invalid version"));
115         break;
116       case PCDM_RS_NoModel:
117         Events_Error::send(std::string("Can not open document: no data model"));
118         break;
119       case PCDM_RS_NoDocument:
120         Events_Error::send(std::string("Can not open document: no document inside"));
121         break;
122       case PCDM_RS_FormatFailure:
123         Events_Error::send(std::string("Can not open document: format failure"));
124         break;
125       case PCDM_RS_TypeNotFoundInSchema:
126         Events_Error::send(std::string("Can not open document: invalid object"));
127         break;
128       case PCDM_RS_UnrecognizedFileFormat:
129         Events_Error::send(std::string("Can not open document: unrecognized file format"));
130         break;
131       case PCDM_RS_MakeFailure:
132         Events_Error::send(std::string("Can not open document: make failure"));
133         break;
134       case PCDM_RS_PermissionDenied:
135         Events_Error::send(std::string("Can not open document: permission denied"));
136         break;
137       case PCDM_RS_DriverFailure:
138         Events_Error::send(std::string("Can not open document: driver failure"));
139         break;
140       default:
141         Events_Error::send(std::string("Can not open document: unknown error"));
142         break;
143     }
144   }
145   if (!isError) {
146     myDoc->SetUndoLimit(UNDO_LIMIT);
147     // to avoid the problem that feature is created in the current, not this, document
148     Model_Session::get()->setActiveDocument(anApp->getDocument(myID));
149     synchronizeFeatures();
150   }
151   return !isError;
152 }
153
154 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
155 {
156   // create a directory in the root document if it is not yet exist
157   if (this == Model_Session::get()->moduleDocument().get()) {
158 #ifdef WIN32
159     CreateDirectory(theFileName, NULL);
160 #else
161     mkdir(theFileName, 0x1ff);
162 #endif
163   }
164   // filename in the dir is id of document inside of the given directory
165   TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
166   PCDM_StoreStatus aStatus;
167   try {
168     aStatus = Model_Application::getApplication()->SaveAs(myDoc, aPath);
169   } catch (Standard_Failure) {
170     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
171     Events_Error::send(
172         std::string("Exception in saving of document: ") + aFail->GetMessageString());
173     return false;
174   }
175   bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
176   if (!isDone) {
177     switch (aStatus) {
178       case PCDM_SS_DriverFailure:
179         Events_Error::send(std::string("Can not save document: save driver-library failure"));
180         break;
181       case PCDM_SS_WriteFailure:
182         Events_Error::send(std::string("Can not save document: file writing failure"));
183         break;
184       case PCDM_SS_Failure:
185       default:
186         Events_Error::send(std::string("Can not save document"));
187         break;
188     }
189   }
190   myTransactionsAfterSave = 0;
191   if (isDone) {  // save also sub-documents if any
192     theResults.push_back(TCollection_AsciiString(aPath).ToCString());
193     std::set<std::string>::iterator aSubIter = mySubs.begin();
194     for (; aSubIter != mySubs.end() && isDone; aSubIter++) {
195       isDone = subDoc(*aSubIter)->save(theFileName, theResults);
196     }
197   }
198   return isDone;
199 }
200
201 void Model_Document::close()
202 {
203   boost::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
204   if (this != aPM->moduleDocument().get() && this == aPM->activeDocument().get()) {
205     aPM->setActiveDocument(aPM->moduleDocument());
206   }
207   // close all subs
208   std::set<std::string>::iterator aSubIter = mySubs.begin();
209   for (; aSubIter != mySubs.end(); aSubIter++)
210     subDoc(*aSubIter)->close();
211   mySubs.clear();
212   // close this
213   /* do not close because it can be undoed
214    if (myDoc->CanClose() == CDM_CCS_OK)
215    myDoc->Close();
216    Model_Application::getApplication()->deleteDocument(myID);
217    */
218 }
219
220 void Model_Document::startOperation()
221 {
222   if (myDoc->HasOpenCommand()) {  // start of nested command
223     if (myNestedNum == -1) {
224       myNestedNum = 0;
225       myDoc->InitDeltaCompaction();
226     }
227     myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand();
228     myTransactionsAfterSave++;
229     myDoc->OpenCommand();
230   } else {  // start the simple command
231     myDoc->NewCommand();
232   }
233   // new command for all subs
234   std::set<std::string>::iterator aSubIter = mySubs.begin();
235   for (; aSubIter != mySubs.end(); aSubIter++)
236     subDoc(*aSubIter)->startOperation();
237 }
238
239 bool Model_Document::compactNested()
240 {
241   bool allWasEmpty = true;
242   while (myNestedNum != -1) {
243     myTransactionsAfterSave--;
244     if (!myIsEmptyTr[myTransactionsAfterSave]) {
245       allWasEmpty = false;
246     }
247     myIsEmptyTr.erase(myTransactionsAfterSave);
248     myNestedNum--;
249   }
250   myIsEmptyTr[myTransactionsAfterSave] = allWasEmpty;
251   myTransactionsAfterSave++;
252   myDoc->PerformDeltaCompaction();
253   return !allWasEmpty;
254 }
255
256 void Model_Document::finishOperation()
257 {
258   // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
259   std::set<std::string>::iterator aSubIter = mySubs.begin();
260   for (; aSubIter != mySubs.end(); aSubIter++)
261     subDoc(*aSubIter)->finishOperation();
262
263   // just to be sure that everybody knows that changes were performed
264   if (!myDoc->HasOpenCommand() && myNestedNum != -1)
265     boost::static_pointer_cast<Model_Session>(Model_Session::get())
266         ->setCheckTransactions(false);  // for nested transaction commit
267   Events_Loop* aLoop = Events_Loop::loop();
268   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
269   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
270   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
271   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
272   if (!myDoc->HasOpenCommand() && myNestedNum != -1)
273     boost::static_pointer_cast<Model_Session>(Model_Session::get())
274         ->setCheckTransactions(true);  // for nested transaction commit
275
276   if (myNestedNum != -1)  // this nested transaction is owervritten
277     myNestedNum++;
278   if (!myDoc->HasOpenCommand()) {
279     if (myNestedNum != -1) {
280       myNestedNum--;
281       compactNested();
282     }
283   } else {
284     // returns false if delta is empty and no transaction was made
285     myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand();  // && (myNestedNum == -1);
286     myTransactionsAfterSave++;
287   }
288
289 }
290
291 void Model_Document::abortOperation()
292 {
293   if (myNestedNum > 0 && !myDoc->HasOpenCommand()) {  // abort all what was done in nested
294       // first compact all nested
295     if (compactNested()) {
296       // for nested it is undo and clear redos
297       myDoc->Undo();
298     }
299     myDoc->ClearRedos();
300     myTransactionsAfterSave--;
301     myIsEmptyTr.erase(myTransactionsAfterSave);
302   } else {
303     if (myNestedNum == 0)  // abort only high-level
304       myNestedNum = -1;
305     myDoc->AbortCommand();
306   }
307   synchronizeFeatures(true);
308   // abort for all subs
309   std::set<std::string>::iterator aSubIter = mySubs.begin();
310   for (; aSubIter != mySubs.end(); aSubIter++)
311     subDoc(*aSubIter)->abortOperation();
312 }
313
314 bool Model_Document::isOperation()
315 {
316   // operation is opened for all documents: no need to check subs
317   return myDoc->HasOpenCommand() == Standard_True ;
318 }
319
320 bool Model_Document::isModified()
321 {
322   // is modified if at least one operation was commited and not undoed
323   return myTransactionsAfterSave > 0 || isOperation();
324 }
325
326 bool Model_Document::canUndo()
327 {
328   if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0
329       && myTransactionsAfterSave != 0 /* for omitting the first useless transaction */)
330     return true;
331   // check other subs contains operation that can be undoed
332   std::set<std::string>::iterator aSubIter = mySubs.begin();
333   for (; aSubIter != mySubs.end(); aSubIter++)
334     if (subDoc(*aSubIter)->canUndo())
335       return true;
336   return false;
337 }
338
339 void Model_Document::undo()
340 {
341   myTransactionsAfterSave--;
342   if (myNestedNum > 0)
343     myNestedNum--;
344   if (!myIsEmptyTr[myTransactionsAfterSave])
345     myDoc->Undo();
346   synchronizeFeatures(true);
347   // undo for all subs
348   std::set<std::string>::iterator aSubIter = mySubs.begin();
349   for (; aSubIter != mySubs.end(); aSubIter++)
350     subDoc(*aSubIter)->undo();
351 }
352
353 bool Model_Document::canRedo()
354 {
355   if (myDoc->GetAvailableRedos() > 0)
356     return true;
357   // check other subs contains operation that can be redoed
358   std::set<std::string>::iterator aSubIter = mySubs.begin();
359   for (; aSubIter != mySubs.end(); aSubIter++)
360     if (subDoc(*aSubIter)->canRedo())
361       return true;
362   return false;
363 }
364
365 void Model_Document::redo()
366 {
367   if (myNestedNum != -1)
368     myNestedNum++;
369   if (!myIsEmptyTr[myTransactionsAfterSave])
370     myDoc->Redo();
371   myTransactionsAfterSave++;
372   synchronizeFeatures(true);
373   // redo for all subs
374   std::set<std::string>::iterator aSubIter = mySubs.begin();
375   for (; aSubIter != mySubs.end(); aSubIter++)
376     subDoc(*aSubIter)->redo();
377 }
378
379 /// Appenad to the array of references a new referenced label
380 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
381 {
382   Handle(TDataStd_ReferenceArray) aRefs;
383   if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
384     aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
385     aRefs->SetValue(0, theReferenced);
386   } else {  // extend array by one more element
387     Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
388                                                                         aRefs->Upper() + 1);
389     for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
390       aNewArray->SetValue(a, aRefs->Value(a));
391     }
392     aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
393     aRefs->SetInternalArray(aNewArray);
394   }
395 }
396
397 FeaturePtr Model_Document::addFeature(std::string theID)
398 {
399   TDF_Label anEmptyLab;
400   FeaturePtr anEmptyFeature;
401   FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
402   if (!aFeature)
403     return aFeature;
404   boost::shared_ptr<Model_Document> aDocToAdd = boost::dynamic_pointer_cast<Model_Document>(
405       aFeature->documentToAdd());
406   if (aFeature) {
407     TDF_Label aFeatureLab;
408     if (!aFeature->isAction()) {  // do not add action to the data model
409       TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
410       aFeatureLab = aFeaturesLab.NewChild();
411       aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
412       // keep the feature ID to restore document later correctly
413       TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
414       aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
415       // store feature in the history of features array
416       if (aFeature->isInHistory()) {
417         AddToRefArray(aFeaturesLab, aFeatureLab);
418       }
419     }
420     if (!aFeature->isAction()) {  // do not add action to the data model
421       // event: feature is added
422       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
423       ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
424     } else { // feature must be executed
425        // no creation event => updater not working, problem with remove part
426       aFeature->execute();
427     }
428   }
429   return aFeature;
430 }
431
432 /// Appenad to the array of references a new referenced label.
433 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
434 /// \returns the index of removed element
435 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
436                                   -1)
437 {
438   int aResult = -1;  // no returned
439   Handle(TDataStd_ReferenceArray) aRefs;
440   if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
441     if (aRefs->Length() == 1) {  // just erase an array
442       if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
443         theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
444       }
445       aResult = 0;
446     } else {  // reduce the array
447       Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
448                                                                           aRefs->Upper() - 1);
449       int aCount = aRefs->Lower();
450       for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
451         if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
452           aCount--;
453           aResult = a;
454         } else {
455           aNewArray->SetValue(aCount, aRefs->Value(a));
456         }
457       }
458       aRefs->SetInternalArray(aNewArray);
459     }
460   }
461   return aResult;
462 }
463
464 void Model_Document::removeFeature(FeaturePtr theFeature, const bool theCheck)
465 {
466   if (theCheck) {
467     // check the feature: it must have no depended objects on it
468     std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
469     for(; aResIter != theFeature->results().cend(); aResIter++) {
470       if (myConcealedResults.find(*aResIter) != myConcealedResults.end()) {
471         Events_Error::send("Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
472         return;
473       }
474     }
475     NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myObjs);
476     for(; anObjIter.More(); anObjIter.Next()) {
477       DataPtr aData = anObjIter.Value()->data();
478       if (aData->referencesTo(theFeature)) {
479         Events_Error::send("Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
480         return;
481       }
482     }
483   }
484
485   boost::shared_ptr<Model_Data> aData = boost::static_pointer_cast<Model_Data>(theFeature->data());
486   TDF_Label aFeatureLabel = aData->label().Father();
487   if (myObjs.IsBound(aFeatureLabel))
488     myObjs.UnBind(aFeatureLabel);
489   else
490     return;  // not found feature => do not remove
491   // erase fields
492   theFeature->erase();
493   // erase all attributes under the label of feature
494   aFeatureLabel.ForgetAllAttributes();
495   // remove it from the references array
496   RemoveFromRefArray(featuresLabel(), aFeatureLabel);
497
498   // event: feature is deleted
499   ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
500   /* this is in "erase"
501   // results of this feature must be redisplayed
502   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
503   const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
504   std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
505   for (; aRIter != aResults.cend(); aRIter++) {
506     boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
507     aRes->setData(boost::shared_ptr<ModelAPI_Data>());  // deleted flag
508     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
509     ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), aRes->groupName());
510   }
511   */
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;
594         if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
595           isIn = myConcealedResults.find(*aRIter) == myConcealedResults.end();
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 = myConcealedResults.find(*aRIter) == myConcealedResults.end();
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->isInHistory() && 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)->isInHistory() && (*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)
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     if (!myObjs.IsBound(aFeatureLabel)) {  // a new feature is inserted
720       // create a feature
721       FeaturePtr aNewObj = ModelAPI_Session::get()->createFeature(
722           TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
723               .ToCString());
724       if (!aNewObj) {  // somethig is wrong, most probably, the opened document has invalid structure
725         Events_Error::send("Invalid type of object in the document");
726         aLabIter.Value()->Label().ForgetAllAttributes();
727         continue;
728       }
729       // this must be before "setData" to redo the sketch line correctly
730       myObjs.Bind(aFeatureLabel, aNewObj);
731       aNewFeatures.insert(aNewObj);
732       initData(aNewObj, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
733
734       // event: model is updated
735       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
736       ModelAPI_EventCreator::get()->sendUpdated(aNewObj, anEvent);
737
738       // update results of the appeared feature
739       updateResults(aNewObj);
740     } else {  // nothing is changed, both iterators are incremented
741       FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
742       aKeptFeatures.insert(aFeature);
743       if (theMarkUpdated) {
744         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
745         ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
746       }
747       updateResults(aFeature);
748     }
749   }
750   // execute new features to restore results: after features creation to make all references valid
751   /*std::set<FeaturePtr>::iterator aNewIter = aNewFeatures.begin();
752    for(; aNewIter != aNewFeatures.end(); aNewIter++) {
753    (*aNewIter)->execute();
754    }*/
755   // check all features are checked: if not => it was removed
756   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
757   while (aFIter.More()) {
758     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
759         && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
760       FeaturePtr aFeature = aFIter.Value();
761       // event: model is updated
762       //if (aFeature->isInHistory()) {
763         ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
764       //}
765       // results of this feature must be redisplayed (hided)
766       static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
767       const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
768       std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
769       /*
770       for (; aRIter != aResults.cend(); aRIter++) {
771         boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
772         //aRes->setData(boost::shared_ptr<ModelAPI_Data>()); // deleted flag
773         ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
774         ModelAPI_EventCreator::get()->sendDeleted(aThis, aRes->groupName());
775       }
776       */
777       // redisplay also removed feature (used for sketch and AISObject)
778       ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
779       aFeature->erase();
780       // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
781       TDF_Label aLab = aFIter.Key();
782       aFIter.Next();
783       myObjs.UnBind(aLab);
784     } else
785       aFIter.Next();
786   }
787
788   myExecuteFeatures = false;
789   aLoop->activateFlushes(true);
790
791   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
792   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
793   if (theMarkUpdated) {
794     aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
795   }
796   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
797   boost::static_pointer_cast<Model_Session>(Model_Session::get())
798     ->setCheckTransactions(true);
799   myExecuteFeatures = true;
800 }
801
802 TDF_Label Model_Document::resultLabel(
803   const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex) 
804 {
805   const boost::shared_ptr<Model_Data>& aData = 
806     boost::dynamic_pointer_cast<Model_Data>(theFeatureData);
807   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
808 }
809
810 void Model_Document::storeResult(boost::shared_ptr<ModelAPI_Data> theFeatureData,
811                                  boost::shared_ptr<ModelAPI_Result> theResult,
812                                  const int theResultIndex)
813 {
814   boost::shared_ptr<ModelAPI_Document> aThis = 
815     Model_Application::getApplication()->getDocument(myID);
816   theResult->setDoc(aThis);
817   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
818   if (theResult->data()->name().empty()) {  // if was not initialized, generate event and set a name
819     theResult->data()->setName(theFeatureData->name());
820   }
821 }
822
823 boost::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
824     const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
825 {
826   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
827   TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
828   ObjectPtr anOldObject = object(aLab);
829   boost::shared_ptr<ModelAPI_ResultConstruction> aResult;
830   if (anOldObject) {
831     aResult = boost::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
832   }
833   if (!aResult) {
834     aResult = boost::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
835     storeResult(theFeatureData, aResult, theIndex);
836   }
837   return aResult;
838 }
839
840 boost::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
841     const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
842 {
843   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
844   TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
845   ObjectPtr anOldObject = object(aLab);
846   boost::shared_ptr<ModelAPI_ResultBody> aResult;
847   if (anOldObject) {
848     aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
849   }
850   if (!aResult) {
851     aResult = boost::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
852     storeResult(theFeatureData, aResult, theIndex);
853   }
854   return aResult;
855 }
856
857 boost::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
858     const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
859 {
860   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
861   TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
862   ObjectPtr anOldObject = object(aLab);
863   boost::shared_ptr<ModelAPI_ResultPart> aResult;
864   if (anOldObject) {
865     aResult = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
866   }
867   if (!aResult) {
868     aResult = boost::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
869     storeResult(theFeatureData, aResult, theIndex);
870   }
871   return aResult;
872 }
873
874 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
875     const boost::shared_ptr<ModelAPI_Result>& theResult)
876 {
877   boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>(theResult->data());
878   if (aData) {
879     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
880     return feature(aFeatureLab);
881   }
882   return FeaturePtr();
883 }
884
885 void Model_Document::updateResults(FeaturePtr theFeature)
886 {
887   // for not persistent is will be done by parametric updater automatically
888   if (!theFeature->isPersistentResult()) return;
889   // check the existing results and remove them if there is nothing on the label
890   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
891   while(aResIter != theFeature->results().cend()) {
892     ResultBodyPtr aBody = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(*aResIter);
893     if (aBody) {
894       if (!aBody->data()->isValid()) { 
895         // found a disappeared result => remove it
896         theFeature->removeResult(aBody);
897         // start iterate from beginning because iterator is corrupted by removing
898         aResIter = theFeature->results().cbegin();
899         continue;
900       }
901     }
902     aResIter++;
903   }
904   // check that results are presented on all labels
905   int aResSize = theFeature->results().size();
906   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
907   for(; aLabIter.More(); aLabIter.Next()) {
908     // here must be GUID of the feature
909     int aResIndex = aLabIter.Value().Tag() - 1;
910     ResultPtr aNewBody;
911     if (aResSize <= aResIndex) {
912       TDF_Label anArgLab = aLabIter.Value();
913       Handle(TDataStd_Comment) aGroup;
914       if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
915         if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
916           aNewBody = createBody(theFeature->data(), aResIndex);
917         } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
918           aNewBody = createPart(theFeature->data(), aResIndex);
919         } else if (aGroup->Get() != ModelAPI_ResultConstruction::group().c_str()) {
920           Events_Error::send(std::string("Unknown type of result is found in the document:") +
921             TCollection_AsciiString(aGroup->Get()).ToCString());
922         }
923       }
924       if (aNewBody) {
925         theFeature->setResult(aNewBody, aResIndex);
926       }
927     }
928   }
929 }
930
931 void Model_Document::objectIsReferenced(const ObjectPtr& theObject)
932 {
933   // only bodies are concealed now
934   ResultBodyPtr aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(theObject);
935   if (aResult) {
936     if (myConcealedResults.find(aResult) != myConcealedResults.end()) {
937       Events_Error::send(std::string("The object '") + aResult->data()->name() +
938         "' is already referenced");
939     } else {
940       myConcealedResults.insert(aResult);
941       boost::shared_ptr<ModelAPI_Document> aThis = 
942         Model_Application::getApplication()->getDocument(myID);
943       ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_ResultBody::group());
944
945       static Events_Loop* aLoop = Events_Loop::loop();
946       static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
947       static const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
948       aECreator->sendUpdated(aResult, EVENT_DISP);
949     }
950   }
951 }
952
953 void Model_Document::objectIsNotReferenced(const ObjectPtr& theObject)
954 {
955   // only bodies are concealed now
956   ResultBodyPtr aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(theObject);
957   if (aResult) {
958     std::set<ResultPtr>::iterator aFind = myConcealedResults.find(aResult);
959     if (aFind != myConcealedResults.end()) {
960       ResultPtr aFeature = *aFind;
961       myConcealedResults.erase(aFind);
962       boost::shared_ptr<ModelAPI_Document> aThis = 
963         Model_Application::getApplication()->getDocument(myID);
964       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
965       ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent, false);
966     } else {
967       Events_Error::send(std::string("The object '") + aResult->data()->name() +
968         "' was not referenced '");
969     }
970   }
971 }
972
973 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
974 {
975   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
976
977 }
978 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
979 {
980   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
981 }