Salome HOME
30bd5e293cceef5d1a5cdf336c346a7665d5c6b2
[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_PluginManager.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 /// Returns the file name of this document by the nameof directory and identifuer of a document
48 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
49 {
50   TCollection_ExtendedString aPath ((const Standard_CString)theFileName);
51   aPath += _separator_;
52   aPath += theID.c_str();
53   aPath += ".cbf"; // standard binary file extension
54   return aPath;
55 }
56
57 bool Model_Document::load(const char* theFileName)
58 {
59   Handle(Model_Application) anApp = Model_Application::getApplication();
60   if (this == Model_PluginManager::get()->rootDocument().get()) {
61     anApp->setLoadPath(theFileName);
62   }
63   TCollection_ExtendedString aPath (DocFileName(theFileName, myID));
64   PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
65   try
66   {
67     aStatus = anApp->Open(aPath, myDoc);
68   }
69   catch (Standard_Failure)
70   {
71     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
72     Events_Error::send(std::string("Exception in opening of document: ") + aFail->GetMessageString());
73     return false;
74   }
75   bool isError = aStatus != PCDM_RS_OK;
76   if (isError)
77   {
78     switch (aStatus)
79     {
80     case PCDM_RS_UnknownDocument: 
81       Events_Error::send(std::string("Can not open document: PCDM_RS_UnknownDocument")); break;
82     case PCDM_RS_AlreadyRetrieved: 
83       Events_Error::send(std::string("Can not open document: PCDM_RS_AlreadyRetrieved")); break;
84     case PCDM_RS_AlreadyRetrievedAndModified:
85       Events_Error::send(
86         std::string("Can not open document: PCDM_RS_AlreadyRetrievedAndModified"));
87       break;
88     case PCDM_RS_NoDriver:
89       Events_Error::send(std::string("Can not open document: PCDM_RS_NoDriver")); break;
90     case PCDM_RS_UnknownFileDriver:
91       Events_Error::send(std::string("Can not open document: PCDM_RS_UnknownFileDriver")); break;
92     case PCDM_RS_OpenError:
93       Events_Error::send(std::string("Can not open document: PCDM_RS_OpenError")); break;
94     case PCDM_RS_NoVersion:
95       Events_Error::send(std::string("Can not open document: PCDM_RS_NoVersion")); break;
96     case PCDM_RS_NoModel:
97       Events_Error::send(std::string("Can not open document: PCDM_RS_NoModel")); break;
98     case PCDM_RS_NoDocument:
99       Events_Error::send(std::string("Can not open document: PCDM_RS_NoDocument")); break;
100     case PCDM_RS_FormatFailure:
101       Events_Error::send(std::string("Can not open document: PCDM_RS_FormatFailure")); break;
102     case PCDM_RS_TypeNotFoundInSchema:
103       Events_Error::send(std::string("Can not open document: PCDM_RS_TypeNotFoundInSchema")); 
104       break;
105     case PCDM_RS_UnrecognizedFileFormat:
106       Events_Error::send(std::string("Can not open document: PCDM_RS_UnrecognizedFileFormat")); 
107       break;
108     case PCDM_RS_MakeFailure:
109       Events_Error::send(std::string("Can not open document: PCDM_RS_MakeFailure")); break;
110     case PCDM_RS_PermissionDenied:
111       Events_Error::send(std::string("Can not open document: PCDM_RS_PermissionDenied")); break;
112     case PCDM_RS_DriverFailure:
113       Events_Error::send(std::string("Can not open document: PCDM_RS_DriverFailure")); break;
114     default:
115       Events_Error::send(std::string("Can not open document: unknown error")); break;
116     }
117   }
118   if (!isError) {
119     myDoc->SetUndoLimit(UNDO_LIMIT);
120     synchronizeFeatures();
121   }
122   return !isError;
123 }
124
125 bool Model_Document::save(const char* theFileName)
126 {
127   // create a directory in the root document if it is not yet exist
128   if (this == Model_PluginManager::get()->rootDocument().get()) {
129 #ifdef WIN32
130     CreateDirectory(theFileName, NULL);
131 #else
132     mkdir(theFileName, 0x1ff); 
133 #endif
134   }
135   // filename in the dir is id of document inside of the given directory
136   TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
137   PCDM_StoreStatus aStatus;
138   try {
139     aStatus = Model_Application::getApplication()->SaveAs(myDoc, aPath);
140   }
141   catch (Standard_Failure) {
142     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
143     Events_Error::send(std::string("Exception in saving of document: ") + aFail->GetMessageString());
144     return false;
145   }
146   bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
147   if (!isDone)
148   {
149     switch (aStatus)
150     {
151     case PCDM_SS_DriverFailure:
152       Events_Error::send(std::string("Can not save document: PCDM_SS_DriverFailure"));
153       break;
154     case PCDM_SS_WriteFailure:
155       Events_Error::send(std::string("Can not save document: PCDM_SS_WriteFailure"));
156       break;
157     case PCDM_SS_Failure:
158     default:
159       Events_Error::send(std::string("Can not save document: PCDM_SS_Failure"));
160       break;
161     }
162   }
163   myTransactionsAfterSave = 0;
164   if (isDone) { // save also sub-documents if any
165     std::set<std::string>::iterator aSubIter = mySubs.begin();
166     for(; aSubIter != mySubs.end() && isDone; aSubIter++)
167       isDone = subDocument(*aSubIter)->save(theFileName);
168   }
169   return isDone;
170 }
171
172 void Model_Document::close()
173 {
174   boost::shared_ptr<ModelAPI_PluginManager> aPM = Model_PluginManager::get();
175   if (this != aPM->rootDocument().get() && 
176       this == aPM->currentDocument().get()) {
177     aPM->setCurrentDocument(aPM->rootDocument());
178   }
179   // close all subs
180   std::set<std::string>::iterator aSubIter = mySubs.begin();
181   for(; aSubIter != mySubs.end(); aSubIter++)
182     subDocument(*aSubIter)->close();
183   mySubs.clear();
184   // close this
185   /* do not close because it can be undoed
186   if (myDoc->CanClose() == CDM_CCS_OK)
187     myDoc->Close();
188   Model_Application::getApplication()->deleteDocument(myID);
189   */
190 }
191
192 void Model_Document::startOperation()
193 {
194   if (myDoc->HasOpenCommand()) { // start of nested command
195     if (myNestedNum == -1) {
196       myNestedNum = 0;
197       myDoc->InitDeltaCompaction();
198     }
199     myIsEmptyTr[myTransactionsAfterSave] = false;
200     myTransactionsAfterSave++;
201     myDoc->NewCommand();
202   } else { // start of simple command
203     myDoc->NewCommand();
204   }
205   // new command for all subs
206   std::set<std::string>::iterator aSubIter = mySubs.begin();
207   for(; aSubIter != mySubs.end(); aSubIter++)
208     subDocument(*aSubIter)->startOperation();
209 }
210
211 void Model_Document::compactNested() {
212   while(myNestedNum != -1) {
213     myTransactionsAfterSave--;
214     myIsEmptyTr.erase(myTransactionsAfterSave);
215     myNestedNum--;
216   }
217   myIsEmptyTr[myTransactionsAfterSave] = false;
218   myTransactionsAfterSave++;
219   myDoc->PerformDeltaCompaction();
220 }
221
222 void Model_Document::finishOperation()
223 {
224   // just to be sure that everybody knows that changes were performed
225   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
226   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
227   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
228   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
229
230   if (myNestedNum != -1) // this nested transaction is owervritten
231     myNestedNum++;
232   if (!myDoc->HasOpenCommand()) {
233     if (myNestedNum != -1) {
234       myNestedNum--;
235       compactNested();
236     }
237   } else {
238     // returns false if delta is empty and no transaction was made
239     myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand() && (myNestedNum == -1);
240     myTransactionsAfterSave++;
241   }
242
243   // finish for all subs
244   std::set<std::string>::iterator aSubIter = mySubs.begin();
245   for(; aSubIter != mySubs.end(); aSubIter++)
246     subDocument(*aSubIter)->finishOperation();
247 }
248
249 void Model_Document::abortOperation()
250 {
251   if (myNestedNum > 0 && !myDoc->HasOpenCommand()) { // abort all what was done in nested
252     // first compact all nested
253     compactNested();
254     // for nested it is undo and clear redos
255     myDoc->Undo();
256     myDoc->ClearRedos();
257     myTransactionsAfterSave--;
258     myIsEmptyTr.erase(myTransactionsAfterSave);
259   } else {
260     if (myNestedNum == 0) // abort only high-level
261       myNestedNum = -1;
262     myDoc->AbortCommand();
263   }
264   synchronizeFeatures(true);
265   // abort for all subs
266   std::set<std::string>::iterator aSubIter = mySubs.begin();
267     for(; aSubIter != mySubs.end(); aSubIter++)
268     subDocument(*aSubIter)->abortOperation();
269 }
270
271 bool Model_Document::isOperation()
272 {
273   // operation is opened for all documents: no need to check subs
274   return myDoc->HasOpenCommand() == Standard_True;
275 }
276
277 bool Model_Document::isModified()
278 {
279   // is modified if at least one operation was commited and not undoed
280   return myTransactionsAfterSave > 0;
281 }
282
283 bool Model_Document::canUndo()
284 {
285   if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0 && myTransactionsAfterSave != 0 /* for omitting the first useless transaction */)
286     return true;
287   // check other subs contains operation that can be undoed
288   std::set<std::string>::iterator aSubIter = mySubs.begin();
289   for(; aSubIter != mySubs.end(); aSubIter++)
290     if (subDocument(*aSubIter)->canUndo())
291       return true;
292   return false;
293 }
294
295 void Model_Document::undo()
296 {
297   myTransactionsAfterSave--;
298   if (myNestedNum > 0) myNestedNum--;
299   if (!myIsEmptyTr[myTransactionsAfterSave])
300     myDoc->Undo();
301   synchronizeFeatures(true);
302   // undo for all subs
303   std::set<std::string>::iterator aSubIter = mySubs.begin();
304   for(; aSubIter != mySubs.end(); aSubIter++)
305     subDocument(*aSubIter)->undo();
306 }
307
308 bool Model_Document::canRedo()
309 {
310   if (myDoc->GetAvailableRedos() > 0)
311     return true;
312   // check other subs contains operation that can be redoed
313   std::set<std::string>::iterator aSubIter = mySubs.begin();
314   for(; aSubIter != mySubs.end(); aSubIter++)
315     if (subDocument(*aSubIter)->canRedo())
316       return true;
317   return false;
318 }
319
320 void Model_Document::redo()
321 {
322   if (myNestedNum != -1) myNestedNum++;
323   if (!myIsEmptyTr[myTransactionsAfterSave])
324     myDoc->Redo();
325   myTransactionsAfterSave++;
326   synchronizeFeatures(true);
327   // redo for all subs
328   std::set<std::string>::iterator aSubIter = mySubs.begin();
329   for(; aSubIter != mySubs.end(); aSubIter++)
330     subDocument(*aSubIter)->redo();
331 }
332
333 /// Appenad to the array of references a new referenced label
334 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced) {
335   Handle(TDataStd_ReferenceArray) aRefs;
336   if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
337     aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
338     aRefs->SetValue(0, theReferenced);
339   } else { // extend array by one more element
340     Handle(TDataStd_HLabelArray1) aNewArray = 
341       new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper() + 1);
342     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
343       aNewArray->SetValue(a, aRefs->Value(a));
344     }
345     aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
346     aRefs->SetInternalArray(aNewArray);
347   }
348 }
349
350 FeaturePtr Model_Document::addFeature(std::string theID)
351 {
352   TDF_Label anEmptyLab;
353   FeaturePtr anEmptyFeature;
354   FeaturePtr aFeature = ModelAPI_PluginManager::get()->createFeature(theID);
355   boost::shared_ptr<Model_Document> aDocToAdd = 
356     boost::dynamic_pointer_cast<Model_Document>(aFeature->documentToAdd());
357   if (aFeature) {
358     TDF_Label aFeatureLab;
359     if (!aFeature->isAction()) {// do not add action to the data model
360       TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
361       aFeatureLab = aFeaturesLab.NewChild();
362       aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
363       // keep the feature ID to restore document later correctly
364       TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
365       aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
366       // store feature in the history of features array
367       if (aFeature->isInHistory()) {
368         AddToRefArray(aFeaturesLab, aFeatureLab);
369       }
370     }
371     if (!aFeature->isAction()) {// do not add action to the data model
372       // event: feature is added
373       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
374       ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
375     }
376   }
377   return aFeature;
378 }
379
380 /// Appenad to the array of references a new referenced label.
381 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
382 /// \returns the index of removed element
383 static int RemoveFromRefArray(
384   TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex = -1) {
385   int aResult = -1; // no returned
386   Handle(TDataStd_ReferenceArray) aRefs;
387   if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
388     if (aRefs->Length() == 1) { // just erase an array
389       if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
390         theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
391       }
392       aResult = 0;
393     } else { // reduce the array
394       Handle(TDataStd_HLabelArray1) aNewArray = 
395         new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper() - 1);
396       int aCount = aRefs->Lower();
397       for(int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
398         if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
399           aCount--;
400           aResult = a;
401         } else {
402           aNewArray->SetValue(aCount, aRefs->Value(a));
403         }
404       }
405       aRefs->SetInternalArray(aNewArray);
406     }
407   }
408   return aResult;
409 }
410
411 void Model_Document::removeFeature(FeaturePtr theFeature)
412 {
413   boost::shared_ptr<Model_Data> aData = boost::static_pointer_cast<Model_Data>(theFeature->data());
414   TDF_Label aFeatureLabel = aData->label().Father();
415   if (myObjs.IsBound(aFeatureLabel)) 
416     myObjs.UnBind(aFeatureLabel);
417   else return; // not found feature => do not remove
418
419   // erase all attributes under the label of feature
420   aFeatureLabel.ForgetAllAttributes();
421   // remove it from the references array
422   RemoveFromRefArray(featuresLabel(), aData->label());
423
424   // event: feature is deleted
425   ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
426   // results of this feature must be redisplayed
427   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
428   const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
429   std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
430   for(; aRIter != aResults.cend(); aRIter++) {
431     boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
432     aRes->setData(boost::shared_ptr<ModelAPI_Data>()); // deleted flag
433     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
434     ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), aRes->groupName());
435   }
436 }
437
438 FeaturePtr Model_Document::feature(TDF_Label& theLabel)
439 {
440   if (myObjs.IsBound(theLabel))
441     return myObjs.Find(theLabel);
442   return FeaturePtr(); // not found
443 }
444
445 ObjectPtr Model_Document::object(TDF_Label theLabel)
446 {
447   // try feature by label
448   FeaturePtr aFeature = feature(theLabel);
449   if (aFeature)
450     return feature(theLabel);
451   TDF_Label aFeatureLabel = theLabel.Father().Father(); // let's suppose it is result
452   aFeature = feature(aFeatureLabel);
453   if (aFeature) {
454     const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
455     std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
456     for(; aRIter != aResults.cend(); aRIter++) {
457       boost::shared_ptr<Model_Data> aResData = 
458         boost::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
459       if (aResData->label().Father().IsEqual(theLabel))
460         return *aRIter;
461     }
462   }
463   return FeaturePtr(); // not found
464 }
465
466 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
467 {
468   // just store sub-document identifier here to manage it later
469   if (mySubs.find(theDocID) == mySubs.end())
470     mySubs.insert(theDocID);
471   return Model_Application::getApplication()->getDocument(theDocID);
472 }
473
474 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex)
475 {
476   if (theGroupID == ModelAPI_Feature::group()) {
477     Handle(TDataStd_ReferenceArray) aRefs;
478     if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
479       return ObjectPtr();
480     if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
481       return ObjectPtr();
482     TDF_Label aFeatureLabel = aRefs->Value(theIndex);
483     return feature(aFeatureLabel);
484   } else {
485     // comment must be in any feature: it is kind
486     int anIndex = 0;
487     TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
488     for(; aLabIter.More(); aLabIter.Next()) {
489       TDF_Label aFLabel = aLabIter.Value()->Label();
490       FeaturePtr aFeature = feature(aFLabel);
491       const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
492       std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
493       for(; aRIter != aResults.cend(); aRIter++) {
494         if ((*aRIter)->isInHistory() && (*aRIter)->groupName() == theGroupID) {
495           if (anIndex == theIndex)
496             return *aRIter;
497           anIndex++;
498         }
499       }
500     }
501   }
502   // not found
503   return ObjectPtr();
504 }
505
506 int Model_Document::size(const std::string& theGroupID) 
507 {
508   int aResult = 0;
509   if (theGroupID == ModelAPI_Feature::group()) {
510     Handle(TDataStd_ReferenceArray) aRefs;
511     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
512       return aRefs->Length();
513   } else {
514     // comment must be in any feature: it is kind
515     TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
516     for(; aLabIter.More(); aLabIter.Next()) {
517       TDF_Label aFLabel = aLabIter.Value()->Label();
518       FeaturePtr aFeature = feature(aFLabel);
519       const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
520       std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
521       for(; aRIter != aResults.cend(); aRIter++) {
522         if ((*aRIter)->isInHistory() && (*aRIter)->groupName() == theGroupID) {
523           aResult++;
524         }
525       }
526     }
527   }
528   // group is not found
529   return aResult;
530 }
531
532 Model_Document::Model_Document(const std::string theID)
533     : myID(theID), myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
534 {
535   myDoc->SetUndoLimit(UNDO_LIMIT);
536   myTransactionsAfterSave = 0;
537   myNestedNum = -1;
538   //myDoc->SetNestedTransactionMode();
539   // to have something in the document and avoid empty doc open/save problem
540   // in transaction for nesting correct working
541   myDoc->NewCommand();
542   TDataStd_Integer::Set(myDoc->Main().Father(), 0);
543   myDoc->CommitCommand();
544 }
545
546 TDF_Label Model_Document::featuresLabel()
547 {
548   return myDoc->Main().FindChild(TAG_OBJECTS);
549 }
550
551 void Model_Document::setUniqueName(FeaturePtr theFeature)
552 {
553   if (!theFeature->data()->name().empty()) return; // not needed, name is already defined
554   std::string aName; // result
555   // first count all objects of such kind to start with index = count + 1
556   int aNumObjects = 0;
557   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
558   for(; aFIter.More(); aFIter.Next()) {
559     if (aFIter.Value()->getKind() == theFeature->getKind())
560       aNumObjects++;
561   }
562   // generate candidate name
563   std::stringstream aNameStream;
564   aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
565   aName = aNameStream.str();
566   // check this is unique, if not, increase index by 1
567   for(aFIter.Initialize(myObjs); aFIter.More(); ) {
568     FeaturePtr aFeature = aFIter.Value();
569     bool isSameName = aFeature->isInHistory() && aFeature->data()->name() == aName;
570     if (!isSameName) { // check also results to avoid same results names (actual for Parts)
571       const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
572       std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
573       for(; aRIter != aResults.cend(); aRIter++) {
574         isSameName = (*aRIter)->isInHistory() && (*aRIter)->data()->name() == aName;
575       }
576     }
577     if (isSameName) {
578       aNumObjects++;
579       std::stringstream aNameStream;
580       aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
581       aName = aNameStream.str();
582       // reinitialize iterator to make sure a new name is unique
583       aFIter.Initialize(myObjs);
584     } else aFIter.Next();
585   }
586   theFeature->data()->setName(aName);
587 }
588
589 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag) {
590   boost::shared_ptr<ModelAPI_Document> aThis = 
591     Model_Application::getApplication()->getDocument(myID);
592   boost::shared_ptr<Model_Data> aData(new Model_Data);
593   aData->setLabel(theLab.FindChild(theTag));
594   aData->setObject(theObj);
595   theObj->setDoc(aThis);
596   theObj->setData(aData);
597   FeaturePtr aFeature = boost::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
598   if (aFeature) {
599     setUniqueName(aFeature); // must be before "initAttributes" because duplicate part uses name
600     aFeature->initAttributes();
601   }
602 }
603
604 void Model_Document::synchronizeFeatures(const bool theMarkUpdated)
605 {
606   boost::shared_ptr<ModelAPI_Document> aThis = 
607     Model_Application::getApplication()->getDocument(myID);
608   // update all objects by checking are they of labels or not
609   std::set<FeaturePtr> aCheckedFeatures;
610   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
611   for(; aLabIter.More(); aLabIter.Next()) {
612     TDF_Label aFeatureLabel = aLabIter.Value()->Label();
613     if (!myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
614       // create a feature
615       FeaturePtr aNewObj = ModelAPI_PluginManager::get()->createFeature(
616         TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
617         .ToCString());
618       // this must be before "setData" to redo the sketch line correctly
619       myObjs.Bind(aFeatureLabel, aNewObj);
620       aCheckedFeatures.insert(aNewObj);
621       initData(aNewObj, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
622       aNewObj->execute(); // to restore results list
623
624       // event: model is updated
625       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
626       ModelAPI_EventCreator::get()->sendUpdated(aNewObj, anEvent);
627       // feature for this label is added, so go to the next label
628     } else { // nothing is changed, both iterators are incremented
629       aCheckedFeatures.insert(myObjs.Find(aFeatureLabel));
630       if (theMarkUpdated) {
631         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
632         ModelAPI_EventCreator::get()->sendUpdated(myObjs.Find(aFeatureLabel), anEvent);
633       }
634     }
635   }
636   // check all features are checked: if not => it was removed
637   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
638   while(aFIter.More()) {
639     if (aCheckedFeatures.find(aFIter.Value()) == aCheckedFeatures.end()) {
640       FeaturePtr aFeature = aFIter.Value();
641       TDF_Label aLab = aFIter.Key();
642       aFIter.Next();
643       myObjs.UnBind(aLab);
644       // event: model is updated
645       if (aFeature->isInHistory()) {
646         ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
647       }
648       // results of this feature must be redisplayed (hided)
649       static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
650       const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
651       std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
652       for(; aRIter != aResults.cend(); aRIter++) {
653         boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
654         aRes->setData(boost::shared_ptr<ModelAPI_Data>()); // deleted flag
655         ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
656         ModelAPI_EventCreator::get()->sendDeleted(aThis, aRes->groupName());
657       }
658     } else aFIter.Next();
659   }
660
661   // after all updates, sends a message that groups of features were created or updated
662   boost::static_pointer_cast<Model_PluginManager>(Model_PluginManager::get())->
663     setCheckTransactions(false);
664   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
665   if (theMarkUpdated)
666     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
667   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
668   boost::static_pointer_cast<Model_PluginManager>(Model_PluginManager::get())->
669     setCheckTransactions(true);
670 }
671
672 void Model_Document::storeResult(boost::shared_ptr<ModelAPI_Data> theFeatureData,
673   boost::shared_ptr<ModelAPI_Result> theResult, const int theResultIndex)
674 {
675   boost::shared_ptr<ModelAPI_Document> aThis = 
676     Model_Application::getApplication()->getDocument(myID);
677   theResult->setDoc(aThis);
678   initData(theResult, boost::dynamic_pointer_cast<Model_Data>(theFeatureData)->label().
679     Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1), TAG_FEATURE_ARGUMENTS);
680   if (theResult->data()->name().empty()) { // if was not initialized, generate event and set a name
681     theResult->data()->setName(theFeatureData->name());
682   }
683 }
684
685 boost::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
686   const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
687 {
688   ObjectPtr anOldObject = object(boost::dynamic_pointer_cast<Model_Data>(theFeatureData)->
689     label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theIndex + 1));
690   boost::shared_ptr<ModelAPI_ResultConstruction> aResult;
691   if (anOldObject) {
692     aResult = boost::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
693   }
694   if (!aResult) {
695     aResult = boost::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
696     storeResult(theFeatureData, aResult);
697   }
698   return aResult;
699 }
700
701 boost::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
702   const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
703 {
704   ObjectPtr anOldObject = object(boost::dynamic_pointer_cast<Model_Data>(theFeatureData)->
705     label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theIndex + 1));
706   boost::shared_ptr<ModelAPI_ResultBody> aResult;
707   if (anOldObject) {
708     aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
709   }
710   if (!aResult) {
711     aResult = boost::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
712     storeResult(theFeatureData, aResult);
713   }
714   return aResult;
715 }
716
717 boost::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
718   const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
719 {
720   ObjectPtr anOldObject = object(boost::dynamic_pointer_cast<Model_Data>(theFeatureData)->
721     label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theIndex + 1));
722   boost::shared_ptr<ModelAPI_ResultPart> aResult;
723   if (anOldObject) {
724     aResult = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
725   }
726   if (!aResult) {
727     aResult = boost::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
728     storeResult(theFeatureData, aResult);
729   }
730   return aResult;
731 }
732
733 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
734   const boost::shared_ptr<ModelAPI_Result>& theResult)
735 {
736   boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>(theResult->data());
737   if (aData) {
738     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
739     return feature(aFeatureLab);
740   }
741   return FeaturePtr();
742 }
743
744 Standard_Integer HashCode(const TDF_Label& theLab,const Standard_Integer theUpper)
745 {
746   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
747
748 }
749 Standard_Boolean IsEqual(const TDF_Label& theLab1,const TDF_Label& theLab2)
750 {
751   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
752 }