Salome HOME
updated copyright message
[modules/shaper.git] / src / Model / Model_Data.cpp
1 // Copyright (C) 2014-2023  CEA, EDF
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       theAttr->id() == "Show_Edges_direction" || theAttr->id() == "Bring_To_Front")) {
470       static const Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
471       ModelAPI_EventCreator::get()->sendUpdated(myObject, anEvent);
472     }
473   }
474 }
475
476 bool Model_Data::blockSendAttributeUpdated(const bool theBlock, const bool theSendMessage)
477 {
478   bool aWasBlocked = !mySendAttributeUpdated;
479   if (mySendAttributeUpdated == theBlock) {
480     mySendAttributeUpdated = !theBlock;
481     if (mySendAttributeUpdated && !myWasChangedButBlocked.empty()) {
482       // so, now it is ok to send the update signal
483       if (theSendMessage) {
484         // make a copy to avoid iteration on modified list
485         // (may be cleared by attribute changed call)
486         std::list<ModelAPI_Attribute*> aWasChangedButBlocked = myWasChangedButBlocked;
487         myWasChangedButBlocked.clear();
488         std::list<ModelAPI_Attribute*>::iterator aChangedIter = aWasChangedButBlocked.begin();
489         for(; aChangedIter != aWasChangedButBlocked.end(); aChangedIter++) {
490           try {
491             myObject->attributeChanged((*aChangedIter)->id());
492           } catch(...) {
493             if (owner().get() && owner()->data().get() && owner()->data()->isValid()) {
494               Events_InfoMessage("Model_Data",
495                 "%1 has failed during the update").arg(owner()->data()->name()).send();
496             }
497           }
498         }
499         static const Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
500         ModelAPI_EventCreator::get()->sendUpdated(myObject, anEvent);
501       } else {
502         myWasChangedButBlocked.clear();
503       }
504     }
505   }
506   return aWasBlocked;
507 }
508
509 void Model_Data::erase()
510 {
511   if (!myLab.IsNull()) {
512     if (myLab.HasAttribute()) {
513       // remove in order to clear back references in other objects
514       std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
515       referencesToObjects(aRefs);
516       std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator
517         anAttrIter = aRefs.begin();
518       for(; anAttrIter != aRefs.end(); anAttrIter++) {
519         std::list<ObjectPtr>::iterator aReferenced = anAttrIter->second.begin();
520         for(; aReferenced != anAttrIter->second.end(); aReferenced++) {
521           if (aReferenced->get() && (*aReferenced)->data()->isValid()) {
522             std::shared_ptr<Model_Data> aData =
523               std::dynamic_pointer_cast<Model_Data>((*aReferenced)->data());
524             aData->removeBackReference(myAttrs[anAttrIter->first].first);
525           }
526         }
527       }
528     }
529     myAttrs.clear();
530     myLab.ForgetAllAttributes();
531   }
532 }
533
534 // indexes in the state array
535 enum StatesIndexes {
536   STATE_INDEX_STATE = 1, // the state type itself
537   STATE_INDEX_TRANSACTION = 2, // transaction ID
538 };
539
540 /// Returns the label array, initializes it by default values if not exists
541 static Handle(TDataStd_IntegerArray) stateArray(TDF_Label& theLab)
542 {
543   Handle(TDataStd_IntegerArray) aStateArray;
544   if (!theLab.FindAttribute(TDataStd_IntegerArray::GetID(), aStateArray)) {
545     aStateArray = TDataStd_IntegerArray::Set(theLab, 1, 2);
546     aStateArray->SetValue(STATE_INDEX_STATE, ModelAPI_StateMustBeUpdated); // default state
547     aStateArray->SetValue(STATE_INDEX_TRANSACTION, 0); // default transaction ID (not existing)
548   }
549   return aStateArray;
550 }
551
552 void Model_Data::execState(const ModelAPI_ExecState theState)
553 {
554   if (theState != ModelAPI_StateNothing) {
555     if (stateArray(myLab)->Value(STATE_INDEX_STATE) != (int)theState) {
556       stateArray(myLab)->SetValue(STATE_INDEX_STATE, (int)theState);
557     }
558   }
559 }
560
561 ModelAPI_ExecState Model_Data::execState()
562 {
563   return ModelAPI_ExecState(stateArray(myLab)->Value(STATE_INDEX_STATE));
564 }
565
566 int Model_Data::updateID()
567 {
568   return stateArray(myLab)->Value(STATE_INDEX_TRANSACTION);
569 }
570
571 void Model_Data::setUpdateID(const int theID)
572 {
573   stateArray(myLab)->SetValue(STATE_INDEX_TRANSACTION, theID);
574 }
575
576 void Model_Data::setError(const std::string& theError, bool theSend)
577 {
578   execState(ModelAPI_StateExecFailed);
579   if (theSend) {
580     Events_InfoMessage("Model_Data", theError).send();
581   }
582   TDataStd_AsciiString::Set(myLab, theError.c_str());
583 }
584
585 void Model_Data::eraseErrorString()
586 {
587   myLab.ForgetAttribute(TDataStd_AsciiString::GetID());
588 }
589
590 std::string Model_Data::error() const
591 {
592   Handle(TDataStd_AsciiString) anErrorAttr;
593   if (myLab.FindAttribute(TDataStd_AsciiString::GetID(), anErrorAttr)) {
594     return std::string(anErrorAttr->Get().ToCString());
595   }
596   return std::string();
597 }
598
599 int Model_Data::featureId() const
600 {
601   return myLab.Father().Tag(); // tag of the feature label
602 }
603
604 void Model_Data::removeBackReference(ObjectPtr theObject, std::string theAttrID)
605 {
606   AttributePtr anAttribute = theObject->data()->attribute(theAttrID);
607   removeBackReference(anAttribute);
608 }
609
610 void Model_Data::removeBackReference(AttributePtr theAttr)
611 {
612   if (myRefsToMe.find(theAttr) == myRefsToMe.end())
613     return;
614
615   myRefsToMe.erase(theAttr);
616
617   // remove concealment immediately: on deselection it must be possible to reselect in GUI the same
618   FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(theAttr->owner());
619   if (aFeatureOwner.get() &&
620     ModelAPI_Session::get()->validators()->isConcealed(aFeatureOwner->getKind(), theAttr->id())) {
621     updateConcealmentFlag();
622   }
623 }
624
625 void Model_Data::addBackReference(FeaturePtr theFeature, std::string theAttrID,
626    const bool theApplyConcealment)
627 {
628   addBackReference(ObjectPtr(theFeature), theAttrID);
629
630   if (theApplyConcealment &&  theFeature->isStable() &&
631       ModelAPI_Session::get()->validators()->isConcealed(theFeature->getKind(), theAttrID)) {
632     std::shared_ptr<ModelAPI_Result> aRes = std::dynamic_pointer_cast<ModelAPI_Result>(myObject);
633     // the second condition is for history upper than concealment causer, so the feature result may
634     // be displayed and previewed; also for avoiding of quick show/hide on history
635     // moving deep down
636     if (aRes && !theFeature->isDisabled()) {
637       aRes->setIsConcealed(true, theFeature->getKind() == "RemoveResults");
638     }
639   }
640 }
641
642 void Model_Data::addBackReference(ObjectPtr theObject, std::string theAttrID)
643 {
644   // it is possible to add the same attribute twice: may be last time the owner was not Stable...
645   AttributePtr anAttribute = theObject->data()->attribute(theAttrID);
646   if (myRefsToMe.find(anAttribute) == myRefsToMe.end())
647     myRefsToMe.insert(anAttribute);
648 }
649
650 void Model_Data::updateConcealmentFlag()
651 {
652   std::set<AttributePtr>::iterator aRefsIter = myRefsToMe.begin();
653   for(; aRefsIter != myRefsToMe.end(); aRefsIter++) {
654     if (aRefsIter->get()) {
655       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefsIter)->owner());
656       if (aFeature.get() && !aFeature->isDisabled() && aFeature->isStable()) {
657         ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
658         bool isCase = aValidators->isCase(aFeature, (*aRefsIter)->id());
659         bool isConcealed = aValidators->isConcealed(aFeature->getKind(), (*aRefsIter)->id());
660         if (isCase && isConcealed) {
661           std::shared_ptr<ModelAPI_Result> aRes =
662             std::dynamic_pointer_cast<ModelAPI_Result>(myObject);
663           if (aRes.get()) {
664             if (aRes->groupName() != ModelAPI_ResultConstruction::group()) {
665               aRes->setIsConcealed(true); // set concealed
666               return;
667             } else if (aFeature->getKind() == "RemoveResults") {
668               aRes->setIsConcealed(true, true);
669               return;
670             }
671           }
672         }
673       }
674     }
675   }
676   std::shared_ptr<ModelAPI_Result> aRes =
677     std::dynamic_pointer_cast<ModelAPI_Result>(myObject);
678   if (aRes.get()) {
679     aRes->setIsConcealed(false);
680   }
681 }
682
683 std::set<std::wstring> set_union(const std::set<std::wstring>& theLeft,
684                                  const std::set<std::wstring>& theRight)
685 {
686   std::set<std::wstring> aResult;
687   aResult.insert(theLeft.begin(), theLeft.end());
688   aResult.insert(theRight.begin(), theRight.end());
689   return aResult;
690 }
691
692 std::set<std::wstring> usedParameters(const AttributePointPtr& theAttribute)
693 {
694   std::set<std::wstring> anUsedParameters;
695   for (int aComponent = 0; aComponent < 3; ++aComponent)
696     anUsedParameters = set_union(anUsedParameters, theAttribute->usedParameters(aComponent));
697   return anUsedParameters;
698 }
699
700 std::set<std::wstring> usedParameters(const AttributePoint2DPtr& theAttribute)
701 {
702   std::set<std::wstring> anUsedParameters;
703   for (int aComponent = 0; aComponent < 2; ++aComponent)
704     anUsedParameters = set_union(anUsedParameters, theAttribute->usedParameters(aComponent));
705   return anUsedParameters;
706 }
707
708 std::list<ResultParameterPtr> findVariables(const std::set<std::wstring>& theParameters,
709                                             const DocumentPtr& theDocument)
710 {
711   std::list<ResultParameterPtr> aResult;
712   std::set<std::wstring>::const_iterator aParamIt = theParameters.cbegin();
713   for (; aParamIt != theParameters.cend(); ++aParamIt) {
714     const std::wstring& aName = *aParamIt;
715     double aValue;
716     ResultParameterPtr aParam;
717     // theSearcher is not needed here: in expressions
718     // of features the parameters history is not needed
719     if (ModelAPI_Tools::findVariable(FeaturePtr(), aName, aValue, aParam, theDocument))
720       aResult.push_back(aParam);
721   }
722   return aResult;
723 }
724
725 void Model_Data::referencesToObjects(
726   std::list<std::pair<std::string, std::list<ObjectPtr> > >& theRefs)
727 {
728   static Model_ValidatorsFactory* aValidators =
729     static_cast<Model_ValidatorsFactory*>(ModelAPI_Session::get()->validators());
730   FeaturePtr aMyFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(myObject);
731
732   AttributeMap::iterator anAttrIt = myAttrs.begin();
733   std::list<ObjectPtr> aReferenced; // not inside of cycle to avoid excess memory management
734   for(; anAttrIt != myAttrs.end(); anAttrIt++) {
735     AttributePtr anAttr = anAttrIt->second.first;
736     // skip not-case attributes, that really may refer to anything not-used (issue 671)
737     if (aMyFeature.get() && !aValidators->isCase(aMyFeature, anAttr->id()))
738       continue;
739
740     std::string aType = anAttr->attributeType();
741     if (aType == ModelAPI_AttributeReference::typeId()) { // reference to object
742       std::shared_ptr<ModelAPI_AttributeReference> aRef = std::dynamic_pointer_cast<
743           ModelAPI_AttributeReference>(anAttr);
744       aReferenced.push_back(aRef->value());
745     } else if (aType == ModelAPI_AttributeRefAttr::typeId()) { // reference to attribute or object
746       std::shared_ptr<ModelAPI_AttributeRefAttr> aRef = std::dynamic_pointer_cast<
747           ModelAPI_AttributeRefAttr>(anAttr);
748       if (aRef->isObject()) {
749         aReferenced.push_back(aRef->object());
750       } else {
751         AttributePtr aReferredAttr = aRef->attr();
752         if (aReferredAttr.get())
753           aReferenced.push_back(aReferredAttr->owner());
754       }
755     } else if (aType == ModelAPI_AttributeRefList::typeId()) { // list of references
756       aReferenced = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(anAttr)->list();
757     }
758     else if (aType == ModelAPI_AttributeSelection::typeId()) { // selection attribute
759       std::shared_ptr<ModelAPI_AttributeSelection> aRef = std::dynamic_pointer_cast<
760         ModelAPI_AttributeSelection>(anAttr);
761       FeaturePtr aRefFeat = aRef->contextFeature();
762       if (aRefFeat.get()) { // reference to all results of the referenced feature
763         const std::list<ResultPtr>& allRes = aRefFeat->results();
764         std::list<ResultPtr>::const_iterator aRefRes = allRes.cbegin();
765         for(; aRefRes != allRes.cend(); aRefRes++) {
766           aReferenced.push_back(*aRefRes);
767         }
768       } else {
769         aReferenced.push_back(aRef->context());
770       }
771     } else if (aType == ModelAPI_AttributeSelectionList::typeId()) { // list of selection attributes
772       std::shared_ptr<ModelAPI_AttributeSelectionList> aRef = std::dynamic_pointer_cast<
773           ModelAPI_AttributeSelectionList>(anAttr);
774       for(int a = 0, aSize = aRef->size(); a < aSize; ++a) {
775         FeaturePtr aRefFeat = aRef->value(a)->contextFeature();
776         if (aRefFeat.get()) { // reference to all results of the referenced feature
777           const std::list<ResultPtr>& allRes = aRefFeat->results();
778           std::list<ResultPtr>::const_iterator aRefRes = allRes.cbegin();
779           for (; aRefRes != allRes.cend(); aRefRes++) {
780             aReferenced.push_back(*aRefRes);
781           }
782         } else {
783           aReferenced.push_back(aRef->value(a)->context());
784         }
785       }
786     } else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
787       std::shared_ptr<ModelAPI_AttributeRefAttrList> aRefAttr = std::dynamic_pointer_cast<
788           ModelAPI_AttributeRefAttrList>(anAttr);
789       std::list<std::pair<ObjectPtr, AttributePtr> > aRefs = aRefAttr->list();
790       std::list<std::pair<ObjectPtr, AttributePtr> >::const_iterator anIt = aRefs.begin(),
791                                                                      aLast = aRefs.end();
792       for (; anIt != aLast; anIt++) {
793         aReferenced.push_back(anIt->first);
794       }
795     } else if (aType == ModelAPI_AttributeInteger::typeId()) { // integer attribute
796       AttributeIntegerPtr anAttribute =
797           std::dynamic_pointer_cast<ModelAPI_AttributeInteger>(anAttr);
798       std::set<std::wstring> anUsedParameters = anAttribute->usedParameters();
799       std::list<ResultParameterPtr> aParameters =
800         findVariables(anUsedParameters, owner()->document());
801       aReferenced.insert(aReferenced.end(), aParameters.begin(), aParameters.end());
802     } else if (aType == ModelAPI_AttributeDouble::typeId()) { // double attribute
803       AttributeDoublePtr anAttribute =
804           std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(anAttr);
805       std::set<std::wstring> anUsedParameters = anAttribute->usedParameters();
806       std::list<ResultParameterPtr> aParameters =
807         findVariables(anUsedParameters, owner()->document());
808       aReferenced.insert(aReferenced.end(), aParameters.begin(), aParameters.end());
809     } else if (aType == GeomDataAPI_Point::typeId()) { // point attribute
810       AttributePointPtr anAttribute =
811         std::dynamic_pointer_cast<GeomDataAPI_Point>(anAttr);
812       std::set<std::wstring> anUsedParameters = usedParameters(anAttribute);
813       std::list<ResultParameterPtr> aParameters =
814         findVariables(anUsedParameters, owner()->document());
815       aReferenced.insert(aReferenced.end(), aParameters.begin(), aParameters.end());
816     } else if (aType == GeomDataAPI_Point2D::typeId()) { // point attribute
817       AttributePoint2DPtr anAttribute =
818         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttr);
819       std::set<std::wstring> anUsedParameters = usedParameters(anAttribute);
820       std::list<ResultParameterPtr> aParameters =
821         findVariables(anUsedParameters, owner()->document());
822       aReferenced.insert(aReferenced.end(), aParameters.begin(), aParameters.end());
823     } else
824       continue; // nothing to do, not reference
825
826     if (!aReferenced.empty()) {
827       theRefs.push_back(
828           std::pair<std::string, std::list<ObjectPtr> >(anAttrIt->first, aReferenced));
829       aReferenced.clear();
830     }
831   }
832 }
833
834 void Model_Data::copyTo(std::shared_ptr<ModelAPI_Data> theTarget)
835 {
836   TDF_Label aTargetRoot = std::dynamic_pointer_cast<Model_Data>(theTarget)->label();
837   Model_Tools::copyAttrs(myLab, aTargetRoot);
838   // reinitialize Model_Attributes by TDF_Attributes set
839   std::shared_ptr<Model_Data> aTData = std::dynamic_pointer_cast<Model_Data>(theTarget);
840   aTData->myAttrs.clear();
841   theTarget->owner()->initAttributes(); // reinitialize feature attributes
842 }
843
844 bool Model_Data::isInHistory()
845 {
846   return myFlags->Value(kFlagInHistory) == Standard_True;
847 }
848
849 void Model_Data::setIsInHistory(const bool theFlag)
850 {
851   return myFlags->SetValue(kFlagInHistory, theFlag);
852 }
853
854 bool Model_Data::isDeleted()
855 {
856   return myFlags->Value(kFlagDeleted) == Standard_True;
857 }
858
859 void Model_Data::setIsDeleted(const bool theFlag)
860 {
861   return myFlags->SetValue(kFlagDeleted, theFlag);
862 }
863
864 bool Model_Data::isDisplayed()
865 {
866   if (!myObject.get() || !myObject->document().get() || // object is in valid
867       myFlags->Value(kFlagDisplayed) != Standard_True) // or it was not displayed before
868     return false;
869   if (myObject->document()->isActive()) // for active documents it must be ok anyway
870     return true;
871   // any object from the root document except part result may be displayed
872   if (myObject->document() == ModelAPI_Session::get()->moduleDocument() &&
873       myObject->groupName() != ModelAPI_ResultPart::group())
874     return true;
875   return false;
876 }
877
878 void Model_Data::setDisplayed(const bool theDisplay)
879 {
880   if (theDisplay != isDisplayed()) {
881     myFlags->SetValue(kFlagDisplayed, theDisplay);
882     static Events_Loop* aLoop = Events_Loop::loop();
883     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
884     static const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
885     aECreator->sendUpdated(myObject, EVENT_DISP);
886   }
887 }
888
889 std::shared_ptr<ModelAPI_Data> Model_Data::invalidPtr()
890 {
891   return kInvalid;
892 }
893
894 std::shared_ptr<ModelAPI_Data> Model_Data::invalidData()
895 {
896   return kInvalid;
897 }
898
899 std::shared_ptr<ModelAPI_Object> Model_Data::owner()
900 {
901   return myObject;
902 }
903
904 bool Model_Data::isPrecedingAttribute(const std::string& theAttribute1,
905                                       const std::string& theAttribute2) const
906 {
907   AttributeMap::const_iterator aFound1 = myAttrs.find(theAttribute1);
908   AttributeMap::const_iterator aFound2 = myAttrs.find(theAttribute2);
909   if (aFound2 == myAttrs.end())
910     return true;
911   else if (aFound1 == myAttrs.end())
912     return false;
913   return aFound1->second.second < aFound2->second.second;
914 }