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