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