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