Salome HOME
2f1eb6f9556aba2f499b19711fc5baa8618381c9
[modules/shaper.git] / src / Model / Model_Data.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        Model_Data.hxx
4 // Created:     21 Mar 2014
5 // Author:      Mikhail PONIKAROV
6
7 #include <Model_Data.h>
8 #include <Model_AttributeDocRef.h>
9 #include <Model_AttributeInteger.h>
10 #include <Model_AttributeDouble.h>
11 #include <Model_AttributeReference.h>
12 #include <Model_AttributeRefAttr.h>
13 #include <Model_AttributeRefList.h>
14 #include <Model_AttributeBoolean.h>
15 #include <Model_AttributeString.h>
16 #include <Model_AttributeSelection.h>
17 #include <Model_AttributeSelectionList.h>
18 #include <Model_AttributeIntArray.h>
19 #include <Model_Events.h>
20 #include <ModelAPI_Feature.h>
21 #include <ModelAPI_Result.h>
22 #include <ModelAPI_Validator.h>
23 #include <ModelAPI_Session.h>
24 #include <ModelAPI_ResultPart.h>
25
26 #include <GeomData_Point.h>
27 #include <GeomData_Point2D.h>
28 #include <GeomData_Dir.h>
29 #include <Events_Loop.h>
30 #include <Events_Error.h>
31
32 #include <TDataStd_Name.hxx>
33 #include <TDataStd_AsciiString.hxx>
34 #include <TDataStd_IntegerArray.hxx>
35 #include <TDF_AttributeIterator.hxx>
36 #include <TDF_ChildIterator.hxx>
37 #include <TDF_RelocationTable.hxx>
38
39 #include <string>
40
41 // myLab contains:
42 // TDataStd_Name - name of the object
43 // TDataStd_IntegerArray - state of the object execution, transaction ID of update
44 // TDataStd_BooleanArray - array of flags of this data:
45 //                             0 - is in history or not
46 static const int kFlagInHistory = 0;
47 //                             1 - is displayed or not
48 static const int kFlagDisplayed = 1;
49
50 // invalid data
51 const static std::shared_ptr<ModelAPI_Data> kInvalid(new Model_Data());
52
53 Model_Data::Model_Data() : mySendAttributeUpdated(true)
54 {
55 }
56
57 void Model_Data::setLabel(TDF_Label theLab)
58 {
59   myLab = theLab;
60   // set or get the default flags
61   if (!myLab.FindAttribute(TDataStd_BooleanArray::GetID(), myFlags)) {
62     // set default values if not found
63     myFlags = TDataStd_BooleanArray::Set(myLab, 0, 1);
64     myFlags->SetValue(kFlagInHistory, Standard_True); // is in history by default is true
65     myFlags->SetValue(kFlagDisplayed, Standard_True); // is displayed by default is true
66   }
67 }
68
69 std::string Model_Data::name()
70 {
71   Handle(TDataStd_Name) aName;
72   if (myLab.FindAttribute(TDataStd_Name::GetID(), aName))
73     return std::string(TCollection_AsciiString(aName->Get()).ToCString());
74   return "";  // not defined
75 }
76
77 void Model_Data::setName(const std::string& theName)
78 {
79   bool isModified = false;
80   std::string anOldName = name();
81   Handle(TDataStd_Name) aName;
82   if (!myLab.FindAttribute(TDataStd_Name::GetID(), aName)) {
83     TDataStd_Name::Set(myLab, theName.c_str());
84     isModified = true;
85   } else {
86     isModified = !aName->Get().IsEqual(theName.c_str());
87     if (isModified)
88       aName->Set(theName.c_str());
89   }
90   if (mySendAttributeUpdated && isModified)
91     ModelAPI_ObjectRenamedMessage::send(myObject, anOldName, theName, this);
92 }
93
94 AttributePtr Model_Data::addAttribute(const std::string& theID, const std::string theAttrType)
95 {
96   AttributePtr aResult;
97   TDF_Label anAttrLab = myLab.FindChild(myAttrs.size() + 1);
98   ModelAPI_Attribute* anAttr = 0;
99   if (theAttrType == ModelAPI_AttributeDocRef::typeId()) {
100     anAttr = new Model_AttributeDocRef(anAttrLab);
101   } else if (theAttrType == Model_AttributeInteger::typeId()) {
102     anAttr = new Model_AttributeInteger(anAttrLab);
103   } else if (theAttrType == ModelAPI_AttributeDouble::typeId()) {
104     anAttr = new Model_AttributeDouble(anAttrLab);
105   } else if (theAttrType == Model_AttributeBoolean::typeId()) {
106     anAttr = new Model_AttributeBoolean(anAttrLab);
107   } else if (theAttrType == Model_AttributeString::typeId()) {
108     anAttr = new Model_AttributeString(anAttrLab);
109   } else if (theAttrType == ModelAPI_AttributeReference::typeId()) {
110     anAttr = new Model_AttributeReference(anAttrLab);
111   } else if (theAttrType == ModelAPI_AttributeSelection::typeId()) {
112     anAttr = new Model_AttributeSelection(anAttrLab);
113   } else if (theAttrType == ModelAPI_AttributeSelectionList::typeId()) {
114     anAttr = new Model_AttributeSelectionList(anAttrLab);
115   } else if (theAttrType == ModelAPI_AttributeRefAttr::typeId()) {
116     anAttr = new Model_AttributeRefAttr(anAttrLab);
117   } else if (theAttrType == ModelAPI_AttributeRefList::typeId()) {
118     anAttr = new Model_AttributeRefList(anAttrLab);
119   } else if (theAttrType == ModelAPI_AttributeIntArray::typeId()) {
120     anAttr = new Model_AttributeIntArray(anAttrLab);
121   } 
122   // create also GeomData attributes here because only here the OCAF strucure is known
123   else if (theAttrType == GeomData_Point::typeId()) {
124     anAttr = new GeomData_Point(anAttrLab);
125   } else if (theAttrType == GeomData_Dir::typeId()) {
126     anAttr = new GeomData_Dir(anAttrLab);
127   } else if (theAttrType == GeomData_Point2D::typeId()) {
128     anAttr = new GeomData_Point2D(anAttrLab);
129   }
130   if (anAttr) {
131     aResult = std::shared_ptr<ModelAPI_Attribute>(anAttr);
132     myAttrs[theID] = aResult;
133     anAttr->setObject(myObject);
134     anAttr->setID(theID);
135   } else {
136     Events_Error::send("Can not create unknown type of attribute " + theAttrType);
137   }
138   return aResult;
139 }
140
141 // macro for gthe generic returning of the attribute by the ID
142 #define GET_ATTRIBUTE_BY_ID(ATTR_TYPE, METHOD_NAME) \
143   std::shared_ptr<ATTR_TYPE> Model_Data::METHOD_NAME(const std::string& theID) { \
144     std::shared_ptr<ATTR_TYPE> aRes; \
145     std::map<std::string, AttributePtr >::iterator aFound = \
146       myAttrs.find(theID); \
147     if (aFound != myAttrs.end()) { \
148       aRes = std::dynamic_pointer_cast<ATTR_TYPE>(aFound->second); \
149     } \
150     return aRes; \
151   }
152 // implement nice getting methods for all ModelAPI attributes
153 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeDocRef, document);
154 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeDouble, real);
155 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeInteger, integer);
156 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeBoolean, boolean);
157 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeString, string);
158 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeReference, reference);
159 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeSelection, selection);
160 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeSelectionList, selectionList);
161 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeRefAttr, refattr);
162 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeRefList, reflist);
163 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeIntArray, intArray);
164
165 std::shared_ptr<ModelAPI_Attribute> Model_Data::attribute(const std::string& theID)
166 {
167   std::shared_ptr<ModelAPI_Attribute> aResult;
168   if (myAttrs.find(theID) == myAttrs.end())  // no such attribute
169     return aResult;
170   return myAttrs[theID];
171 }
172
173 const std::string& Model_Data::id(const std::shared_ptr<ModelAPI_Attribute>& theAttr)
174 {
175   std::map<std::string, std::shared_ptr<ModelAPI_Attribute> >::iterator anAttr = 
176     myAttrs.begin();
177   for (; anAttr != myAttrs.end(); anAttr++) {
178     if (anAttr->second == theAttr)
179       return anAttr->first;
180   }
181   // not found
182   static std::string anEmpty;
183   return anEmpty;
184 }
185
186 bool Model_Data::isEqual(const std::shared_ptr<ModelAPI_Data>& theData)
187 {
188   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theData);
189   if (aData)
190     return myLab.IsEqual(aData->myLab) == Standard_True ;
191   return false;
192 }
193
194 bool Model_Data::isValid()
195 {
196   return !myLab.IsNull() && myLab.HasAttribute();
197 }
198
199 std::list<std::shared_ptr<ModelAPI_Attribute> > Model_Data::attributes(const std::string& theType)
200 {
201   std::list<std::shared_ptr<ModelAPI_Attribute> > aResult;
202   std::map<std::string, std::shared_ptr<ModelAPI_Attribute> >::iterator anAttrsIter = 
203     myAttrs.begin();
204   for (; anAttrsIter != myAttrs.end(); anAttrsIter++) {
205     if (theType.empty() || anAttrsIter->second->attributeType() == theType) {
206       aResult.push_back(anAttrsIter->second);
207     }
208   }
209   return aResult;
210 }
211
212 std::list<std::string> Model_Data::attributesIDs(const std::string& theType) 
213 {
214   std::list<std::string> aResult;
215   std::map<std::string, std::shared_ptr<ModelAPI_Attribute> >::iterator anAttrsIter = 
216     myAttrs.begin();
217   for (; anAttrsIter != myAttrs.end(); anAttrsIter++) {
218     if (theType.empty() || anAttrsIter->second->attributeType() == theType) {
219       aResult.push_back(anAttrsIter->first);
220     }
221   }
222   return aResult;
223 }
224
225 void Model_Data::sendAttributeUpdated(ModelAPI_Attribute* theAttr)
226 {
227   theAttr->setInitialized();
228   if (theAttr->isArgument()) {
229     static const Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
230     ModelAPI_EventCreator::get()->sendUpdated(myObject, anEvent);
231     if (mySendAttributeUpdated && myObject) {
232       myObject->attributeChanged(theAttr->id());
233     }
234   }
235 }
236
237 void Model_Data::blockSendAttributeUpdated(const bool theBlock)
238 {
239   mySendAttributeUpdated = !theBlock;
240 }
241
242 void Model_Data::erase()
243 {
244   if (!myLab.IsNull())
245     myLab.ForgetAllAttributes();
246 }
247
248 // indexes in the state array
249 enum StatesIndexes {
250   STATE_INDEX_STATE = 1, // the state type itself
251   STATE_INDEX_TRANSACTION = 2, // transaction ID
252 };
253
254 /// Returns the label array, initialises it by default values if not exists
255 static Handle(TDataStd_IntegerArray) stateArray(TDF_Label& theLab)
256 {
257   Handle(TDataStd_IntegerArray) aStateArray;
258   if (!theLab.FindAttribute(TDataStd_IntegerArray::GetID(), aStateArray)) {
259     aStateArray = TDataStd_IntegerArray::Set(theLab, 1, 2);
260     aStateArray->SetValue(STATE_INDEX_STATE, ModelAPI_StateMustBeUpdated); // default state
261     aStateArray->SetValue(STATE_INDEX_TRANSACTION, 0); // default transaction ID (not existing)
262   }
263   return aStateArray;
264 }
265
266 void Model_Data::execState(const ModelAPI_ExecState theState)
267 {
268   if (theState != ModelAPI_StateNothing) {
269     stateArray(myLab)->SetValue(STATE_INDEX_STATE, (int)theState);
270   }
271 }
272
273 ModelAPI_ExecState Model_Data::execState()
274 {
275   return ModelAPI_ExecState(stateArray(myLab)->Value(STATE_INDEX_STATE));
276 }
277
278 int Model_Data::updateID()
279 {
280   return stateArray(myLab)->Value(STATE_INDEX_TRANSACTION);
281 }
282
283 void Model_Data::setUpdateID(const int theID)
284 {
285   stateArray(myLab)->SetValue(STATE_INDEX_TRANSACTION, theID);
286 }
287
288 void Model_Data::setError(const std::string& theError, bool theSend)
289 {
290   execState(ModelAPI_StateExecFailed);
291   if (theSend) {
292     Events_Error::send(theError);
293   }
294   TDataStd_AsciiString::Set(myLab, theError.c_str());
295 }
296
297 std::string Model_Data::error() const
298 {
299   Handle(TDataStd_AsciiString) anErrorAttr;
300   if (myLab.FindAttribute(TDataStd_AsciiString::GetID(), anErrorAttr)) {
301     return std::string(anErrorAttr->Get().ToCString());
302   }
303   return std::string();
304 }
305
306 int Model_Data::featureId() const
307 {
308   return myLab.Father().Tag(); // tag of the feature label
309 }
310
311 void Model_Data::eraseBackReferences()
312 {
313   myRefsToMe.clear();
314   std::shared_ptr<ModelAPI_Result> aRes = 
315     std::dynamic_pointer_cast<ModelAPI_Result>(myObject);
316   if (aRes)
317     aRes->setIsConcealed(false);
318 }
319
320 void Model_Data::removeBackReference(FeaturePtr theFeature, std::string theAttrID)
321 {
322   AttributePtr anAttribute = theFeature->data()->attribute(theAttrID);
323   if (myRefsToMe.find(anAttribute) == myRefsToMe.end())
324     return;
325
326   myRefsToMe.erase(anAttribute);
327
328   // remove concealment immideately: on deselection it must be posible to reselect in GUI the same
329   if (ModelAPI_Session::get()->validators()->isConcealed(theFeature->getKind(), theAttrID)) {
330     updateConcealmentFlag();
331   }
332 }
333
334 void Model_Data::addBackReference(FeaturePtr theFeature, std::string theAttrID, 
335    const bool theApplyConcealment)
336 {
337   // do not add the same attribute twice
338   AttributePtr anAttribute = theFeature->data()->attribute(theAttrID);
339   if (myRefsToMe.find(anAttribute) != myRefsToMe.end())
340     return;
341
342   myRefsToMe.insert(theFeature->data()->attribute(theAttrID));
343   if (theApplyConcealment && 
344       ModelAPI_Session::get()->validators()->isConcealed(theFeature->getKind(), theAttrID)) {
345     std::shared_ptr<ModelAPI_Result> aRes = 
346       std::dynamic_pointer_cast<ModelAPI_Result>(myObject);
347     // the second condition is for history upper than concealment causer, so the feature result may
348     // be displayed and previewed; also for avoiding of quick show/hide on history
349     // moving deep down
350     if (aRes && !theFeature->isDisabled()) {
351       aRes->setIsConcealed(true);
352     }
353   }
354 }
355
356 void Model_Data::updateConcealmentFlag()
357 {
358   std::set<AttributePtr>::iterator aRefsIter = myRefsToMe.begin();
359   for(; aRefsIter != myRefsToMe.end(); aRefsIter++) {
360     if (aRefsIter->get()) {
361       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefsIter)->owner());
362       if (aFeature.get() && !aFeature->isDisabled()) {
363         if (ModelAPI_Session::get()->validators()->isConcealed(
364               aFeature->getKind(), (*aRefsIter)->id())) {
365           return; // it is still concealed, nothing to do
366         }
367       }
368     }
369   }
370   // thus, no concealment references anymore => make not-concealed
371   std::shared_ptr<ModelAPI_Result> aRes = 
372     std::dynamic_pointer_cast<ModelAPI_Result>(myObject);
373   if (aRes.get()) {
374     aRes->setIsConcealed(false);
375     static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
376     ModelAPI_EventCreator::get()->sendUpdated(aRes, anEvent);
377     Events_Loop::loop()->flush(anEvent);
378   }
379 }
380
381 #include <Model_Validator.h>
382
383 void Model_Data::referencesToObjects(
384   std::list<std::pair<std::string, std::list<ObjectPtr> > >& theRefs)
385 {
386   static Model_ValidatorsFactory* aValidators = 
387     static_cast<Model_ValidatorsFactory*>(ModelAPI_Session::get()->validators());
388   FeaturePtr aMyFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(myObject);
389
390   std::map<std::string, std::shared_ptr<ModelAPI_Attribute> >::iterator anAttr = myAttrs.begin();
391   std::list<ObjectPtr> aReferenced; // not inside of cycle to avoid excess memory menagement
392   for(; anAttr != myAttrs.end(); anAttr++) {
393     // skip not-case attributres, that really may refer to anything not-used (issue 671)
394     if (aMyFeature.get() && !aValidators->isCase(aMyFeature, anAttr->second->id()))
395       continue;
396
397     std::string aType = anAttr->second->attributeType();
398     if (aType == ModelAPI_AttributeReference::typeId()) { // reference to object
399       std::shared_ptr<ModelAPI_AttributeReference> aRef = std::dynamic_pointer_cast<
400           ModelAPI_AttributeReference>(anAttr->second);
401       aReferenced.push_back(aRef->value());
402     } else if (aType == ModelAPI_AttributeRefAttr::typeId()) { // reference to attribute or object
403       std::shared_ptr<ModelAPI_AttributeRefAttr> aRef = std::dynamic_pointer_cast<
404           ModelAPI_AttributeRefAttr>(anAttr->second);
405       aReferenced.push_back(aRef->isObject() ? aRef->object() : aRef->attr()->owner());
406     } else if (aType == ModelAPI_AttributeRefList::typeId()) { // list of references
407       aReferenced = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(anAttr->second)->list();
408     } else if (aType == ModelAPI_AttributeSelection::typeId()) { // selection attribute
409       std::shared_ptr<ModelAPI_AttributeSelection> aRef = std::dynamic_pointer_cast<
410           ModelAPI_AttributeSelection>(anAttr->second);
411       aReferenced.push_back(aRef->context());
412     } else if (aType == ModelAPI_AttributeSelectionList::typeId()) { // list of selection attributes
413       std::shared_ptr<ModelAPI_AttributeSelectionList> aRef = std::dynamic_pointer_cast<
414           ModelAPI_AttributeSelectionList>(anAttr->second);
415       for(int a = aRef->size() - 1; a >= 0; a--) {
416         aReferenced.push_back(aRef->value(a)->context());
417       }
418     } else
419       continue; // nothing to do, not reference
420
421     if (!aReferenced.empty()) {
422       theRefs.push_back(std::pair<std::string, std::list<ObjectPtr> >(anAttr->first, aReferenced));
423       aReferenced.clear();
424     }
425   }
426 }
427
428 /// makes copy of all attributes on the given label and all sub-labels
429 static void copyAttrs(TDF_Label theSource, TDF_Label theDestination) {
430   TDF_AttributeIterator anAttrIter(theSource);
431   for(; anAttrIter.More(); anAttrIter.Next()) {
432     Handle(TDF_Attribute) aTargetAttr;
433     if (!theDestination.FindAttribute(anAttrIter.Value()->ID(), aTargetAttr)) {
434       // create a new attribute if not yet exists in the destination
435             aTargetAttr = anAttrIter.Value()->NewEmpty();
436       theDestination.AddAttribute(aTargetAttr);
437     }
438     Handle(TDF_RelocationTable) aRelocTable = new TDF_RelocationTable(); // no relocation, empty map
439     anAttrIter.Value()->Paste(aTargetAttr, aRelocTable);
440   }
441   // copy the sub-labels content
442   TDF_ChildIterator aSubLabsIter(theSource);
443   for(; aSubLabsIter.More(); aSubLabsIter.Next()) {
444     copyAttrs(aSubLabsIter.Value(), theDestination.FindChild(aSubLabsIter.Value().Tag()));
445   }
446 }
447
448 void Model_Data::copyTo(std::shared_ptr<ModelAPI_Data> theTarget)
449 {
450   TDF_Label aTargetRoot = std::dynamic_pointer_cast<Model_Data>(theTarget)->label();
451   copyAttrs(myLab, aTargetRoot);
452   // make initialized the initialized attributes
453   std::map<std::string, std::shared_ptr<ModelAPI_Attribute> >::iterator aMyIter = myAttrs.begin();
454   for(; aMyIter != myAttrs.end(); aMyIter++) {
455     if (aMyIter->second->isInitialized()) {
456       theTarget->attribute(aMyIter->first)->setInitialized();
457     }
458   }
459 }
460
461 bool Model_Data::isInHistory()
462 {
463   return myFlags->Value(kFlagInHistory) == Standard_True;
464 }
465
466 void Model_Data::setIsInHistory(const bool theFlag)
467 {
468   return myFlags->SetValue(kFlagInHistory, theFlag);
469 }
470
471 bool Model_Data::isDisplayed()
472 {
473   if (!myObject.get() || !myObject->document().get() || // object is in valid
474       myFlags->Value(kFlagDisplayed) != Standard_True) // or it was not displayed before
475     return false;
476   if (myObject->document()->isActive()) // for active documents it must be ok anyway
477     return true;
478   // any object from the root document except part result may be displayed
479   if (myObject->document() == ModelAPI_Session::get()->moduleDocument() &&
480       myObject->groupName() != ModelAPI_ResultPart::group())
481     return true;
482   return false;
483 }
484
485 void Model_Data::setDisplayed(const bool theDisplay)
486 {
487   if (theDisplay != isDisplayed()) {
488     myFlags->SetValue(kFlagDisplayed, theDisplay);
489     static Events_Loop* aLoop = Events_Loop::loop();
490     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
491     static const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
492     aECreator->sendUpdated(myObject, EVENT_DISP);
493   }
494 }
495
496 std::shared_ptr<ModelAPI_Data> Model_Data::invalidPtr()
497 {
498   return kInvalid;
499 }
500
501 std::shared_ptr<ModelAPI_Data> Model_Data::invalidData()
502 {
503   return kInvalid;
504 }
505
506 bool Model_Data::isOwner(ModelAPI_Object* theOwner)
507 {
508   return theOwner == myObject.get();
509 }