Salome HOME
45798a12fc36a93d98911e2e3cc0cfa6b8c0a38f
[modules/shaper.git] / src / Model / Model_Data.cpp
1 // Copyright (C) 2014-2019  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include <Model_Data.h>
21 #include <Model_AttributeDocRef.h>
22 #include <Model_AttributeInteger.h>
23 #include <Model_AttributeDouble.h>
24 #include <Model_AttributeDoubleArray.h>
25 #include <Model_AttributeReference.h>
26 #include <Model_AttributeRefAttr.h>
27 #include <Model_AttributeRefList.h>
28 #include <Model_AttributeRefAttrList.h>
29 #include <Model_AttributeBoolean.h>
30 #include <Model_AttributeString.h>
31 #include <Model_AttributeStringArray.h>
32 #include <Model_AttributeSelection.h>
33 #include <Model_AttributeSelectionList.h>
34 #include <Model_AttributeIntArray.h>
35 #include <Model_AttributeTables.h>
36 #include <Model_Events.h>
37 #include <Model_Expression.h>
38 #include <Model_Tools.h>
39 #include <Model_Validator.h>
40
41 #include <ModelAPI_Feature.h>
42 #include <ModelAPI_Result.h>
43 #include <ModelAPI_ResultParameter.h>
44 #include <ModelAPI_ResultConstruction.h>
45 #include <ModelAPI_Validator.h>
46 #include <ModelAPI_Session.h>
47 #include <ModelAPI_ResultPart.h>
48 #include <ModelAPI_Tools.h>
49
50 #include <GeomDataAPI_Point.h>
51 #include <GeomDataAPI_Point2D.h>
52
53 #include <GeomData_Point.h>
54 #include <GeomData_Point2D.h>
55 #include <GeomData_Dir.h>
56 #include <Events_Loop.h>
57 #include <Events_InfoMessage.h>
58
59 #include <TDataStd_Name.hxx>
60 #include <TDataStd_AsciiString.hxx>
61 #include <TDataStd_UAttribute.hxx>
62 #include <TDF_ChildIDIterator.hxx>
63
64 #include <string>
65
66 // myLab contains:
67 // TDataStd_Name - name of the object
68 // TDataStd_IntegerArray - state of the object execution, transaction ID of update
69 // TDataStd_BooleanArray - array of flags of this data:
70 //                             0 - is in history or not
71 static const int kFlagInHistory = 0;
72 //                             1 - is displayed or not
73 static const int kFlagDisplayed = 1;
74 //                             2 - is deleted (for results) or not
75 static const int kFlagDeleted = 2;
76 // TDataStd_Integer - 0 if the name of the object is generated automatically,
77 //                    otherwise the name is defined by user
78 Standard_GUID kUSER_DEFINED_NAME("9c694d18-a83c-4a56-bc9b-8020628a8244");
79
80 // invalid data
81 const static std::shared_ptr<ModelAPI_Data> kInvalid(new Model_Data());
82
83 static const Standard_GUID kGroupAttributeGroupID("df64ea4c-fc42-4bf8-ad7e-08f7a54bf1b8");
84 static const Standard_GUID kGroupAttributeID("ebdcb22a-e045-455b-9a7f-cfd38d68e185");
85
86
87 Model_Data::Model_Data() : mySendAttributeUpdated(true), myWasChangedButBlocked(false)
88 {
89 }
90
91 void Model_Data::setLabel(TDF_Label theLab)
92 {
93   myLab = theLab;
94   // set or get the default flags
95   if (!myLab.FindAttribute(TDataStd_BooleanArray::GetID(), myFlags)) {
96     // set default values if not found
97     myFlags = TDataStd_BooleanArray::Set(myLab, 0, 2);
98     myFlags->SetValue(kFlagInHistory, Standard_True); // is in history by default is true
99     myFlags->SetValue(kFlagDisplayed, Standard_True); // is displayed by default is true
100     myFlags->SetValue(kFlagDeleted, Standard_False); // is deleted by default is false
101   }
102 }
103
104 std::string Model_Data::name()
105 {
106   Handle(TDataStd_Name) aName;
107   if (shapeLab().FindAttribute(TDataStd_Name::GetID(), aName)) {
108 #ifdef DEBUG_NAMES
109     myObject->myName = TCollection_AsciiString(aName->Get()).ToCString();
110 #endif
111     return std::string(TCollection_AsciiString(aName->Get()).ToCString());
112   }
113   return "";  // not defined
114 }
115
116 void Model_Data::setName(const std::string& theName)
117 {
118   bool isModified = false;
119   std::string anOldName = name();
120   Handle(TDataStd_Name) aName;
121   if (!shapeLab().FindAttribute(TDataStd_Name::GetID(), aName)) {
122     TDataStd_Name::Set(shapeLab(), theName.c_str());
123     isModified = true;
124   } else {
125     isModified = !aName->Get().IsEqual(theName.c_str());
126     if (isModified) {
127       aName->Set(theName.c_str());
128
129       // check the name of result is defined by user
130       // (name of result does not composed of the name of feature and the result index)
131       bool isUserDefined = true;
132       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myObject);
133       if (aResult) {
134         std::string aDefaultName = ModelAPI_Tools::getDefaultName(aResult, false).first;
135         isUserDefined = aDefaultName != theName;
136       }
137       if (isUserDefined) {
138         // name is user-defined, thus special attribute is set
139         TDataStd_UAttribute::Set(shapeLab(), kUSER_DEFINED_NAME);
140       }
141     }
142   }
143   if (mySendAttributeUpdated && isModified)
144     ModelAPI_ObjectRenamedMessage::send(myObject, anOldName, theName, this);
145   if (isModified && myObject && myObject->document()) {
146     std::dynamic_pointer_cast<Model_Document>(myObject->document())->
147       changeNamingName(anOldName, theName, shapeLab());
148   }
149 #ifdef DEBUG_NAMES
150   myObject->myName = theName;
151 #endif
152 }
153
154 bool Model_Data::hasUserDefinedName() const
155 {
156   return shapeLab().IsAttribute(kUSER_DEFINED_NAME);
157 }
158
159 AttributePtr Model_Data::addAttribute(
160   const std::string& theID, const std::string theAttrType, const int theIndex)
161 {
162   AttributePtr aResult;
163   int anAttrIndex = theIndex == -1 ? int(myAttrs.size()) + 1 : theIndex;
164   TDF_Label anAttrLab = myLab.FindChild(anAttrIndex);
165   ModelAPI_Attribute* anAttr = 0;
166   if (theAttrType == ModelAPI_AttributeDocRef::typeId()) {
167     anAttr = new Model_AttributeDocRef(anAttrLab);
168   } else if (theAttrType == Model_AttributeInteger::typeId()) {
169     anAttr = new Model_AttributeInteger(anAttrLab);
170   } else if (theAttrType == ModelAPI_AttributeDouble::typeId()) {
171     anAttr = new Model_AttributeDouble(anAttrLab);
172   } else if (theAttrType == Model_AttributeBoolean::typeId()) {
173     anAttr = new Model_AttributeBoolean(anAttrLab);
174   } else if (theAttrType == Model_AttributeString::typeId()) {
175     anAttr = new Model_AttributeString(anAttrLab);
176   } else if (theAttrType == Model_AttributeStringArray::typeId()) {
177     anAttr = new Model_AttributeStringArray(anAttrLab);
178   } else if (theAttrType == ModelAPI_AttributeReference::typeId()) {
179     anAttr = new Model_AttributeReference(anAttrLab);
180   } else if (theAttrType == ModelAPI_AttributeSelection::typeId()) {
181     anAttr = new Model_AttributeSelection(anAttrLab);
182   } else if (theAttrType == ModelAPI_AttributeSelectionList::typeId()) {
183     anAttr = new Model_AttributeSelectionList(anAttrLab);
184   } else if (theAttrType == ModelAPI_AttributeRefAttr::typeId()) {
185     anAttr = new Model_AttributeRefAttr(anAttrLab);
186   } else if (theAttrType == ModelAPI_AttributeRefList::typeId()) {
187     anAttr = new Model_AttributeRefList(anAttrLab);
188   } else if (theAttrType == ModelAPI_AttributeRefAttrList::typeId()) {
189     anAttr = new Model_AttributeRefAttrList(anAttrLab);
190   } else if (theAttrType == ModelAPI_AttributeIntArray::typeId()) {
191     anAttr = new Model_AttributeIntArray(anAttrLab);
192   } else if (theAttrType == ModelAPI_AttributeDoubleArray::typeId()) {
193     anAttr = new Model_AttributeDoubleArray(anAttrLab);
194   } else if (theAttrType == ModelAPI_AttributeTables::typeId()) {
195     anAttr = new Model_AttributeTables(anAttrLab);
196   }
197   // create also GeomData attributes here because only here the OCAF structure is known
198   else if (theAttrType == GeomData_Point::typeId()) {
199     GeomData_Point* anAttribute = new GeomData_Point();
200     bool anAllInitialized = true;
201     for (int aComponent = 0; aComponent < GeomData_Point::NUM_COMPONENTS; ++aComponent) {
202       TDF_Label anExpressionLab = anAttrLab.FindChild(aComponent + 1);
203       anAttribute->myExpression[aComponent].reset(new Model_ExpressionDouble(anExpressionLab));
204       anAllInitialized = anAllInitialized && anAttribute->myExpression[aComponent]->isInitialized();
205     }
206     anAttribute->myIsInitialized = anAllInitialized;
207     anAttr = anAttribute;
208   } else if (theAttrType == GeomData_Dir::typeId()) {
209     anAttr = new GeomData_Dir(anAttrLab);
210   } else if (theAttrType == GeomData_Point2D::typeId()) {
211     GeomData_Point2D* anAttribute = new GeomData_Point2D();
212     bool anAllInitialized = true;
213     for (int aComponent = 0; aComponent < GeomData_Point2D::NUM_COMPONENTS; ++aComponent) {
214       TDF_Label anExpressionLab = anAttrLab.FindChild(aComponent + 1);
215       anAttribute->myExpression[aComponent].reset(new Model_ExpressionDouble(anExpressionLab));
216       anAllInitialized = anAllInitialized && anAttribute->myExpression[aComponent]->isInitialized();
217     }
218     anAttribute->myIsInitialized = anAllInitialized;
219     anAttr = anAttribute;
220   }
221   if (anAttr) {
222     aResult = std::shared_ptr<ModelAPI_Attribute>(anAttr);
223     myAttrs[theID] = std::pair<AttributePtr, int>(aResult, anAttrIndex);
224     anAttr->setObject(myObject);
225     anAttr->setID(theID);
226   } else {
227     Events_InfoMessage("Model_Data",
228       "Can not create unknown type of attribute %1").arg(theAttrType).send();
229   }
230   return aResult;
231 }
232
233 AttributePtr Model_Data::addFloatingAttribute(
234   const std::string& theID, const std::string theAttrType, const std::string& theGroup)
235 {
236   // compute the index of the attribute placement
237   int anIndex;
238   TDF_Label aLab;
239   if (myLab.IsAttribute(TDF_TagSource::GetID())) {
240     // check this is re-init of attributes, so, check attribute with this name already there
241     TDF_ChildIDIterator anIter(myLab, kGroupAttributeID, false);
242     for(; anIter.More(); anIter.Next()) {
243       TCollection_AsciiString aThisName(Handle(TDataStd_Name)::DownCast(anIter.Value())->Get());
244       if (theID == aThisName.ToCString()) {
245         TDF_Label aLab = anIter.Value()->Label();
246         Handle(TDataStd_Name) aGName;
247         if (aLab.FindAttribute(kGroupAttributeGroupID, aGName)) {
248           TCollection_AsciiString aGroupName(aGName->Get());
249           if (theGroup == aGroupName.ToCString()) {
250             return addAttribute(theGroup + "__" + theID, theAttrType, aLab.Tag());
251           }
252         }
253       }
254     }
255     aLab = myLab.NewChild(); // already exists a floating attribute, create the next
256     anIndex = aLab.Tag();
257   } else { // put the first floating attribute, quite far from other standard attributes
258     anIndex = int(myAttrs.size()) + 1000;
259     TDF_TagSource::Set(myLab)->Set(anIndex);
260     aLab = myLab.FindChild(anIndex, true);
261   }
262   // store the group ID and the attribute ID (to restore correctly)
263   TDataStd_Name::Set(aLab, kGroupAttributeGroupID, theGroup.c_str());
264   TDataStd_Name::Set(aLab, kGroupAttributeID, theID.c_str());
265
266   return addAttribute(theGroup + "__" + theID, theAttrType, anIndex);
267 }
268
269 void Model_Data::allGroups(std::list<std::string>& theGroups)
270 {
271   std::set<std::string> alreadyThere;
272   for(TDF_ChildIDIterator aGroup(myLab, kGroupAttributeGroupID); aGroup.More(); aGroup.Next()) {
273     Handle(TDataStd_Name) aGroupAttr = Handle(TDataStd_Name)::DownCast(aGroup.Value());
274     std::string aGroupID = TCollection_AsciiString(aGroupAttr->Get()).ToCString();
275     if (alreadyThere.find(aGroupID) == alreadyThere.end()) {
276       theGroups.push_back(aGroupID);
277       alreadyThere.insert(aGroupID);
278     }
279   }
280 }
281
282 void Model_Data::attributesOfGroup(const std::string& theGroup,
283   std::list<std::shared_ptr<ModelAPI_Attribute> >& theAttrs)
284 {
285   for(TDF_ChildIDIterator aGroup(myLab, kGroupAttributeGroupID); aGroup.More(); aGroup.Next()) {
286     Handle(TDataStd_Name) aGroupID = Handle(TDataStd_Name)::DownCast(aGroup.Value());
287     if (aGroupID->Get().IsEqual(theGroup.c_str())) {
288       Handle(TDataStd_Name) anID;
289       if (aGroup.Value()->Label().FindAttribute(kGroupAttributeID, anID)) {
290         TCollection_AsciiString anAsciiID(aGroupID->Get() + "__" + anID->Get());
291         theAttrs.push_back(attribute(anAsciiID.ToCString()));
292       }
293     }
294   }
295 }
296
297 void Model_Data::removeAttributes(const std::string& theGroup)
298 {
299   TDF_LabelList aLabsToRemove; // collect labels that must be erased after the cycle
300   for(TDF_ChildIDIterator aGroup(myLab, kGroupAttributeGroupID); aGroup.More(); aGroup.Next()) {
301     Handle(TDataStd_Name) aGroupID = Handle(TDataStd_Name)::DownCast(aGroup.Value());
302     if (aGroupID->Get().IsEqual(theGroup.c_str())) {
303       Handle(TDataStd_Name) anID;
304       if (!aGroup.Value()->Label().IsNull() &&
305           aGroup.Value()->Label().FindAttribute(kGroupAttributeID, anID)) {
306         aLabsToRemove.Append(aGroup.Value()->Label());
307       }
308       TCollection_AsciiString anAsciiID(aGroupID->Get() + "__" + anID->Get());
309       myAttrs.erase(anAsciiID.ToCString());
310     }
311   }
312   for(TDF_LabelList::Iterator aLab(aLabsToRemove); aLab.More(); aLab.Next()) {
313     aLab.ChangeValue().ForgetAllAttributes(true);
314   }
315 }
316
317 void Model_Data::clearAttributes()
318 {
319   myAttrs.clear();
320 }
321
322
323
324 // macro for the generic returning of the attribute by the ID
325 #define GET_ATTRIBUTE_BY_ID(ATTR_TYPE, METHOD_NAME) \
326   std::shared_ptr<ATTR_TYPE> Model_Data::METHOD_NAME(const std::string& theID) { \
327     std::shared_ptr<ATTR_TYPE> aRes; \
328     AttributeMap::iterator aFound = myAttrs.find(theID); \
329     if (aFound != myAttrs.end()) { \
330       aRes = std::dynamic_pointer_cast<ATTR_TYPE>(aFound->second.first); \
331     } \
332     return aRes; \
333   }
334 // implement nice getting methods for all ModelAPI attributes
335 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeDocRef, document);
336 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeDouble, real);
337 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeInteger, integer);
338 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeBoolean, boolean);
339 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeString, string);
340 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeStringArray, stringArray);
341 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeReference, reference);
342 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeSelection, selection);
343 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeSelectionList, selectionList);
344 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeRefAttr, refattr);
345 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeRefList, reflist);
346 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeRefAttrList, refattrlist);
347 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeIntArray, intArray);
348 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeDoubleArray, realArray);
349 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeTables, tables);
350
351 std::shared_ptr<ModelAPI_Attribute> Model_Data::attribute(const std::string& theID)
352 {
353   std::shared_ptr<ModelAPI_Attribute> aResult;
354   if (myAttrs.find(theID) == myAttrs.end())  // no such attribute
355     return aResult;
356   return myAttrs[theID].first;
357 }
358
359 const std::string& Model_Data::id(const std::shared_ptr<ModelAPI_Attribute>& theAttr)
360 {
361   AttributeMap::iterator anAttr = myAttrs.begin();
362   for (; anAttr != myAttrs.end(); anAttr++) {
363     if (anAttr->second.first == theAttr)
364       return anAttr->first;
365   }
366   // not found
367   static std::string anEmpty;
368   return anEmpty;
369 }
370
371 bool Model_Data::isEqual(const std::shared_ptr<ModelAPI_Data>& theData)
372 {
373   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theData);
374   if (aData)
375     return myLab.IsEqual(aData->myLab) == Standard_True ;
376   return false;
377 }
378
379 bool Model_Data::isValid()
380 {
381   return !myLab.IsNull() && myLab.HasAttribute();
382 }
383
384 std::list<std::shared_ptr<ModelAPI_Attribute> > Model_Data::attributes(const std::string& theType)
385 {
386   std::list<std::shared_ptr<ModelAPI_Attribute> > aResult;
387   AttributeMap::iterator anAttrsIter = myAttrs.begin();
388   for (; anAttrsIter != myAttrs.end(); anAttrsIter++) {
389     AttributePtr anAttr = anAttrsIter->second.first;
390     if (theType.empty() || anAttr->attributeType() == theType) {
391       aResult.push_back(anAttr);
392     }
393   }
394   return aResult;
395 }
396
397 std::list<std::string> Model_Data::attributesIDs(const std::string& theType)
398 {
399   std::list<std::string> aResult;
400   AttributeMap::iterator anAttrsIter = myAttrs.begin();
401   for (; anAttrsIter != myAttrs.end(); anAttrsIter++) {
402     AttributePtr anAttr = anAttrsIter->second.first;
403     if (theType.empty() || anAttr->attributeType() == theType) {
404       aResult.push_back(anAttrsIter->first);
405     }
406   }
407   return aResult;
408 }
409
410 void Model_Data::sendAttributeUpdated(ModelAPI_Attribute* theAttr)
411 {
412   theAttr->setInitialized();
413   if (theAttr->isArgument()) {
414     if (mySendAttributeUpdated) {
415       if (myObject) {
416         try {
417             myObject->attributeChanged(theAttr->id());
418         } catch(...) {
419           if (owner().get() && owner()->data().get() && owner()->data()->isValid()) {
420             Events_InfoMessage("Model_Data",
421               "%1 has failed during the update").arg(owner()->data()->name()).send();
422           }
423         }
424         static const Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
425         ModelAPI_EventCreator::get()->sendUpdated(myObject, anEvent);
426       }
427     } else {
428       // to avoid too many duplications do not add the same like the last
429       if (myWasChangedButBlocked.empty() || *(myWasChangedButBlocked.rbegin()) != theAttr)
430         myWasChangedButBlocked.push_back(theAttr);
431     }
432   } else {
433     // trim: need to redisplay or set color in the python script
434     if (myObject && (theAttr->attributeType() == "Point2D" || theAttr->id() == "Color")) {
435       static const Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
436       ModelAPI_EventCreator::get()->sendUpdated(myObject, anEvent);
437     }
438   }
439 }
440
441 bool Model_Data::blockSendAttributeUpdated(const bool theBlock, const bool theSendMessage)
442 {
443   bool aWasBlocked = !mySendAttributeUpdated;
444   if (mySendAttributeUpdated == theBlock) {
445     mySendAttributeUpdated = !theBlock;
446     if (mySendAttributeUpdated && !myWasChangedButBlocked.empty()) {
447       // so, now it is ok to send the update signal
448       if (theSendMessage) {
449         // make a copy to avoid iteration on modified list
450         // (may be cleared by attribute changed call)
451         std::list<ModelAPI_Attribute*> aWasChangedButBlocked = myWasChangedButBlocked;
452         myWasChangedButBlocked.clear();
453         std::list<ModelAPI_Attribute*>::iterator aChangedIter = aWasChangedButBlocked.begin();
454         for(; aChangedIter != aWasChangedButBlocked.end(); aChangedIter++) {
455           try {
456             myObject->attributeChanged((*aChangedIter)->id());
457           } catch(...) {
458             if (owner().get() && owner()->data().get() && owner()->data()->isValid()) {
459               Events_InfoMessage("Model_Data",
460                 "%1 has failed during the update").arg(owner()->data()->name()).send();
461             }
462           }
463         }
464         static const Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
465         ModelAPI_EventCreator::get()->sendUpdated(myObject, anEvent);
466       } else {
467         myWasChangedButBlocked.clear();
468       }
469     }
470   }
471   return aWasBlocked;
472 }
473
474 void Model_Data::erase()
475 {
476   if (!myLab.IsNull()) {
477     if (myLab.HasAttribute()) {
478       // remove in order to clear back references in other objects
479       std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
480       referencesToObjects(aRefs);
481       std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator
482         anAttrIter = aRefs.begin();
483       for(; anAttrIter != aRefs.end(); anAttrIter++) {
484         std::list<ObjectPtr>::iterator aReferenced = anAttrIter->second.begin();
485         for(; aReferenced != anAttrIter->second.end(); aReferenced++) {
486           if (aReferenced->get() && (*aReferenced)->data()->isValid()) {
487             std::shared_ptr<Model_Data> aData =
488               std::dynamic_pointer_cast<Model_Data>((*aReferenced)->data());
489             aData->removeBackReference(myAttrs[anAttrIter->first].first);
490           }
491         }
492       }
493     }
494     myAttrs.clear();
495     myLab.ForgetAllAttributes();
496   }
497 }
498
499 // indexes in the state array
500 enum StatesIndexes {
501   STATE_INDEX_STATE = 1, // the state type itself
502   STATE_INDEX_TRANSACTION = 2, // transaction ID
503 };
504
505 /// Returns the label array, initializes it by default values if not exists
506 static Handle(TDataStd_IntegerArray) stateArray(TDF_Label& theLab)
507 {
508   Handle(TDataStd_IntegerArray) aStateArray;
509   if (!theLab.FindAttribute(TDataStd_IntegerArray::GetID(), aStateArray)) {
510     aStateArray = TDataStd_IntegerArray::Set(theLab, 1, 2);
511     aStateArray->SetValue(STATE_INDEX_STATE, ModelAPI_StateMustBeUpdated); // default state
512     aStateArray->SetValue(STATE_INDEX_TRANSACTION, 0); // default transaction ID (not existing)
513   }
514   return aStateArray;
515 }
516
517 void Model_Data::execState(const ModelAPI_ExecState theState)
518 {
519   if (theState != ModelAPI_StateNothing) {
520     if (stateArray(myLab)->Value(STATE_INDEX_STATE) != (int)theState) {
521       stateArray(myLab)->SetValue(STATE_INDEX_STATE, (int)theState);
522     }
523   }
524 }
525
526 ModelAPI_ExecState Model_Data::execState()
527 {
528   return ModelAPI_ExecState(stateArray(myLab)->Value(STATE_INDEX_STATE));
529 }
530
531 int Model_Data::updateID()
532 {
533   return stateArray(myLab)->Value(STATE_INDEX_TRANSACTION);
534 }
535
536 void Model_Data::setUpdateID(const int theID)
537 {
538   stateArray(myLab)->SetValue(STATE_INDEX_TRANSACTION, theID);
539 }
540
541 void Model_Data::setError(const std::string& theError, bool theSend)
542 {
543   execState(ModelAPI_StateExecFailed);
544   if (theSend) {
545     Events_InfoMessage("Model_Data", theError).send();
546   }
547   TDataStd_AsciiString::Set(myLab, theError.c_str());
548 }
549
550 void Model_Data::eraseErrorString()
551 {
552   myLab.ForgetAttribute(TDataStd_AsciiString::GetID());
553 }
554
555 std::string Model_Data::error() const
556 {
557   Handle(TDataStd_AsciiString) anErrorAttr;
558   if (myLab.FindAttribute(TDataStd_AsciiString::GetID(), anErrorAttr)) {
559     return std::string(anErrorAttr->Get().ToCString());
560   }
561   return std::string();
562 }
563
564 int Model_Data::featureId() const
565 {
566   return myLab.Father().Tag(); // tag of the feature label
567 }
568
569 void Model_Data::removeBackReference(ObjectPtr theObject, std::string theAttrID)
570 {
571   AttributePtr anAttribute = theObject->data()->attribute(theAttrID);
572   removeBackReference(anAttribute);
573 }
574
575 void Model_Data::removeBackReference(AttributePtr theAttr)
576 {
577   if (myRefsToMe.find(theAttr) == myRefsToMe.end())
578     return;
579
580   myRefsToMe.erase(theAttr);
581
582   // remove concealment immediately: on deselection it must be possible to reselect in GUI the same
583   FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(theAttr->owner());
584   if (aFeatureOwner.get() &&
585     ModelAPI_Session::get()->validators()->isConcealed(aFeatureOwner->getKind(), theAttr->id())) {
586     updateConcealmentFlag();
587   }
588 }
589
590 void Model_Data::addBackReference(FeaturePtr theFeature, std::string theAttrID,
591    const bool theApplyConcealment)
592 {
593   addBackReference(ObjectPtr(theFeature), theAttrID);
594
595   if (theApplyConcealment &&  theFeature->isStable() &&
596       ModelAPI_Session::get()->validators()->isConcealed(theFeature->getKind(), theAttrID)) {
597     std::shared_ptr<ModelAPI_Result> aRes = std::dynamic_pointer_cast<ModelAPI_Result>(myObject);
598     // the second condition is for history upper than concealment causer, so the feature result may
599     // be displayed and previewed; also for avoiding of quick show/hide on history
600     // moving deep down
601     if (aRes && !theFeature->isDisabled()) {
602       aRes->setIsConcealed(true, theFeature->getKind() == "RemoveResults");
603     }
604   }
605 }
606
607 void Model_Data::addBackReference(ObjectPtr theObject, std::string theAttrID)
608 {
609   // it is possible to add the same attribute twice: may be last time the owner was not Stable...
610   AttributePtr anAttribute = theObject->data()->attribute(theAttrID);
611   if (myRefsToMe.find(anAttribute) == myRefsToMe.end())
612     myRefsToMe.insert(anAttribute);
613 }
614
615 void Model_Data::updateConcealmentFlag()
616 {
617   std::set<AttributePtr>::iterator aRefsIter = myRefsToMe.begin();
618   for(; aRefsIter != myRefsToMe.end(); aRefsIter++) {
619     if (aRefsIter->get()) {
620       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefsIter)->owner());
621       if (aFeature.get() && !aFeature->isDisabled() && aFeature->isStable()) {
622         if (ModelAPI_Session::get()->validators()->isConcealed(
623               aFeature->getKind(), (*aRefsIter)->id())) {
624           std::shared_ptr<ModelAPI_Result> aRes =
625             std::dynamic_pointer_cast<ModelAPI_Result>(myObject);
626           if (aRes.get()) {
627             if (aRes->groupName() != ModelAPI_ResultConstruction::group()) {
628               aRes->setIsConcealed(true); // set concealed
629               return;
630             } else if (aFeature->getKind() == "RemoveResults") {
631               aRes->setIsConcealed(true, true);
632               return;
633             }
634           }
635         }
636       }
637     }
638   }
639   std::shared_ptr<ModelAPI_Result> aRes =
640     std::dynamic_pointer_cast<ModelAPI_Result>(myObject);
641   if (aRes.get()) {
642     aRes->setIsConcealed(false);
643   }
644 }
645
646 std::set<std::string> set_union(const std::set<std::string>& theLeft,
647                                 const std::set<std::string>& theRight)
648 {
649   std::set<std::string> aResult;
650   aResult.insert(theLeft.begin(), theLeft.end());
651   aResult.insert(theRight.begin(), theRight.end());
652   return aResult;
653 }
654
655 std::set<std::string> usedParameters(const AttributePointPtr& theAttribute)
656 {
657   std::set<std::string> anUsedParameters;
658   for (int aComponent = 0; aComponent < 3; ++aComponent)
659     anUsedParameters = set_union(anUsedParameters, theAttribute->usedParameters(aComponent));
660   return anUsedParameters;
661 }
662
663 std::set<std::string> usedParameters(const AttributePoint2DPtr& theAttribute)
664 {
665   std::set<std::string> anUsedParameters;
666   for (int aComponent = 0; aComponent < 2; ++aComponent)
667     anUsedParameters = set_union(anUsedParameters, theAttribute->usedParameters(aComponent));
668   return anUsedParameters;
669 }
670
671 std::list<ResultParameterPtr> findVariables(const std::set<std::string>& theParameters,
672                                             const DocumentPtr& theDocument)
673 {
674   std::list<ResultParameterPtr> aResult;
675   std::set<std::string>::const_iterator aParamIt = theParameters.cbegin();
676   for (; aParamIt != theParameters.cend(); ++aParamIt) {
677     const std::string& aName = *aParamIt;
678     double aValue;
679     ResultParameterPtr aParam;
680     // theSearcher is not needed here: in expressions
681     // of features the parameters history is not needed
682     if (ModelAPI_Tools::findVariable(FeaturePtr(), aName, aValue, aParam, theDocument))
683       aResult.push_back(aParam);
684   }
685   return aResult;
686 }
687
688 void Model_Data::referencesToObjects(
689   std::list<std::pair<std::string, std::list<ObjectPtr> > >& theRefs)
690 {
691   static Model_ValidatorsFactory* aValidators =
692     static_cast<Model_ValidatorsFactory*>(ModelAPI_Session::get()->validators());
693   FeaturePtr aMyFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(myObject);
694
695   AttributeMap::iterator anAttrIt = myAttrs.begin();
696   std::list<ObjectPtr> aReferenced; // not inside of cycle to avoid excess memory management
697   for(; anAttrIt != myAttrs.end(); anAttrIt++) {
698     AttributePtr anAttr = anAttrIt->second.first;
699     // skip not-case attributes, that really may refer to anything not-used (issue 671)
700     if (aMyFeature.get() && !aValidators->isCase(aMyFeature, anAttr->id()))
701       continue;
702
703     std::string aType = anAttr->attributeType();
704     if (aType == ModelAPI_AttributeReference::typeId()) { // reference to object
705       std::shared_ptr<ModelAPI_AttributeReference> aRef = std::dynamic_pointer_cast<
706           ModelAPI_AttributeReference>(anAttr);
707       aReferenced.push_back(aRef->value());
708     } else if (aType == ModelAPI_AttributeRefAttr::typeId()) { // reference to attribute or object
709       std::shared_ptr<ModelAPI_AttributeRefAttr> aRef = std::dynamic_pointer_cast<
710           ModelAPI_AttributeRefAttr>(anAttr);
711       if (aRef->isObject()) {
712         aReferenced.push_back(aRef->object());
713       } else {
714         AttributePtr anAttr = aRef->attr();
715         if (anAttr.get())
716           aReferenced.push_back(anAttr->owner());
717       }
718     } else if (aType == ModelAPI_AttributeRefList::typeId()) { // list of references
719       aReferenced = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(anAttr)->list();
720     }
721     else if (aType == ModelAPI_AttributeSelection::typeId()) { // selection attribute
722       std::shared_ptr<ModelAPI_AttributeSelection> aRef = std::dynamic_pointer_cast<
723         ModelAPI_AttributeSelection>(anAttr);
724       FeaturePtr aRefFeat = aRef->contextFeature();
725       if (aRefFeat.get()) { // reference to all results of the referenced feature
726         const std::list<ResultPtr>& allRes = aRefFeat->results();
727         std::list<ResultPtr>::const_iterator aRefRes = allRes.cbegin();
728         for(; aRefRes != allRes.cend(); aRefRes++) {
729           aReferenced.push_back(*aRefRes);
730         }
731       } else {
732         aReferenced.push_back(aRef->context());
733       }
734     } else if (aType == ModelAPI_AttributeSelectionList::typeId()) { // list of selection attributes
735       std::shared_ptr<ModelAPI_AttributeSelectionList> aRef = std::dynamic_pointer_cast<
736           ModelAPI_AttributeSelectionList>(anAttr);
737       for(int a = 0, aSize = aRef->size(); a < aSize; ++a) {
738         FeaturePtr aRefFeat = aRef->value(a)->contextFeature();
739         if (aRefFeat.get()) { // reference to all results of the referenced feature
740           const std::list<ResultPtr>& allRes = aRefFeat->results();
741           std::list<ResultPtr>::const_iterator aRefRes = allRes.cbegin();
742           for (; aRefRes != allRes.cend(); aRefRes++) {
743             aReferenced.push_back(*aRefRes);
744           }
745         } else {
746           aReferenced.push_back(aRef->value(a)->context());
747         }
748       }
749     } else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
750       std::shared_ptr<ModelAPI_AttributeRefAttrList> aRefAttr = std::dynamic_pointer_cast<
751           ModelAPI_AttributeRefAttrList>(anAttr);
752       std::list<std::pair<ObjectPtr, AttributePtr> > aRefs = aRefAttr->list();
753       std::list<std::pair<ObjectPtr, AttributePtr> >::const_iterator anIt = aRefs.begin(),
754                                                                      aLast = aRefs.end();
755       for (; anIt != aLast; anIt++) {
756         aReferenced.push_back(anIt->first);
757       }
758     } else if (aType == ModelAPI_AttributeInteger::typeId()) { // integer attribute
759       AttributeIntegerPtr anAttribute =
760           std::dynamic_pointer_cast<ModelAPI_AttributeInteger>(anAttr);
761       std::set<std::string> anUsedParameters = anAttribute->usedParameters();
762       std::list<ResultParameterPtr> aParameters =
763         findVariables(anUsedParameters, owner()->document());
764       aReferenced.insert(aReferenced.end(), aParameters.begin(), aParameters.end());
765     } else if (aType == ModelAPI_AttributeDouble::typeId()) { // double attribute
766       AttributeDoublePtr anAttribute =
767           std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(anAttr);
768       std::set<std::string> anUsedParameters = anAttribute->usedParameters();
769       std::list<ResultParameterPtr> aParameters =
770         findVariables(anUsedParameters, owner()->document());
771       aReferenced.insert(aReferenced.end(), aParameters.begin(), aParameters.end());
772     } else if (aType == GeomDataAPI_Point::typeId()) { // point attribute
773       AttributePointPtr anAttribute =
774         std::dynamic_pointer_cast<GeomDataAPI_Point>(anAttr);
775       std::set<std::string> anUsedParameters = usedParameters(anAttribute);
776       std::list<ResultParameterPtr> aParameters =
777         findVariables(anUsedParameters, owner()->document());
778       aReferenced.insert(aReferenced.end(), aParameters.begin(), aParameters.end());
779     } else if (aType == GeomDataAPI_Point2D::typeId()) { // point attribute
780       AttributePoint2DPtr anAttribute =
781         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttr);
782       std::set<std::string> anUsedParameters = usedParameters(anAttribute);
783       std::list<ResultParameterPtr> aParameters =
784         findVariables(anUsedParameters, owner()->document());
785       aReferenced.insert(aReferenced.end(), aParameters.begin(), aParameters.end());
786     } else
787       continue; // nothing to do, not reference
788
789     if (!aReferenced.empty()) {
790       theRefs.push_back(
791           std::pair<std::string, std::list<ObjectPtr> >(anAttrIt->first, aReferenced));
792       aReferenced.clear();
793     }
794   }
795 }
796
797 void Model_Data::copyTo(std::shared_ptr<ModelAPI_Data> theTarget)
798 {
799   TDF_Label aTargetRoot = std::dynamic_pointer_cast<Model_Data>(theTarget)->label();
800   Model_Tools::copyAttrs(myLab, aTargetRoot);
801   // reinitialize Model_Attributes by TDF_Attributes set
802   std::shared_ptr<Model_Data> aTData = std::dynamic_pointer_cast<Model_Data>(theTarget);
803   aTData->myAttrs.clear();
804   theTarget->owner()->initAttributes(); // reinitialize feature attributes
805 }
806
807 bool Model_Data::isInHistory()
808 {
809   return myFlags->Value(kFlagInHistory) == Standard_True;
810 }
811
812 void Model_Data::setIsInHistory(const bool theFlag)
813 {
814   return myFlags->SetValue(kFlagInHistory, theFlag);
815 }
816
817 bool Model_Data::isDeleted()
818 {
819   return myFlags->Value(kFlagDeleted) == Standard_True;
820 }
821
822 void Model_Data::setIsDeleted(const bool theFlag)
823 {
824   return myFlags->SetValue(kFlagDeleted, theFlag);
825 }
826
827 bool Model_Data::isDisplayed()
828 {
829   if (!myObject.get() || !myObject->document().get() || // object is in valid
830       myFlags->Value(kFlagDisplayed) != Standard_True) // or it was not displayed before
831     return false;
832   if (myObject->document()->isActive()) // for active documents it must be ok anyway
833     return true;
834   // any object from the root document except part result may be displayed
835   if (myObject->document() == ModelAPI_Session::get()->moduleDocument() &&
836       myObject->groupName() != ModelAPI_ResultPart::group())
837     return true;
838   return false;
839 }
840
841 void Model_Data::setDisplayed(const bool theDisplay)
842 {
843   if (theDisplay != isDisplayed()) {
844     myFlags->SetValue(kFlagDisplayed, theDisplay);
845     static Events_Loop* aLoop = Events_Loop::loop();
846     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
847     static const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
848     aECreator->sendUpdated(myObject, EVENT_DISP);
849   }
850 }
851
852 std::shared_ptr<ModelAPI_Data> Model_Data::invalidPtr()
853 {
854   return kInvalid;
855 }
856
857 std::shared_ptr<ModelAPI_Data> Model_Data::invalidData()
858 {
859   return kInvalid;
860 }
861
862 std::shared_ptr<ModelAPI_Object> Model_Data::owner()
863 {
864   return myObject;
865 }
866
867 bool Model_Data::isPrecedingAttribute(const std::string& theAttribute1,
868                                       const std::string& theAttribute2) const
869 {
870   AttributeMap::const_iterator aFound1 = myAttrs.find(theAttribute1);
871   AttributeMap::const_iterator aFound2 = myAttrs.find(theAttribute2);
872   if (aFound2 == myAttrs.end())
873     return true;
874   else if (aFound1 == myAttrs.end())
875     return false;
876   return aFound1->second.second < aFound2->second.second;
877 }