]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_Data.cpp
Salome HOME
Update Filters data model using the previous filters implementation: filter arguments...
[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 <ModelAPI_Feature.h>
39 #include <ModelAPI_Result.h>
40 #include <ModelAPI_ResultParameter.h>
41 #include <ModelAPI_Validator.h>
42 #include <ModelAPI_Session.h>
43 #include <ModelAPI_ResultPart.h>
44 #include <ModelAPI_Tools.h>
45 #include <Model_Validator.h>
46
47 #include <GeomDataAPI_Point.h>
48 #include <GeomDataAPI_Point2D.h>
49
50 #include <GeomData_Point.h>
51 #include <GeomData_Point2D.h>
52 #include <GeomData_Dir.h>
53 #include <Events_Loop.h>
54 #include <Events_InfoMessage.h>
55
56 #include <TDataStd_Name.hxx>
57 #include <TDataStd_AsciiString.hxx>
58 #include <TDataStd_IntegerArray.hxx>
59 #include <TDataStd_UAttribute.hxx>
60 #include <TDF_AttributeIterator.hxx>
61 #include <TDF_ChildIterator.hxx>
62 #include <TDF_RelocationTable.hxx>
63 #include <TDF_ChildIDIterator.hxx>
64 #include <TColStd_HArray1OfByte.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   }
223   if (anAttr) {
224     aResult = std::shared_ptr<ModelAPI_Attribute>(anAttr);
225     myAttrs[theID] = std::pair<AttributePtr, int>(aResult, anAttrIndex);
226     anAttr->setObject(myObject);
227     anAttr->setID(theID);
228   } else {
229     Events_InfoMessage("Model_Data",
230       "Can not create unknown type of attribute %1").arg(theAttrType).send();
231   }
232   return aResult;
233 }
234
235 AttributePtr Model_Data::addFloatingAttribute(
236   const std::string& theID, const std::string theAttrType, const std::string& theGroup)
237 {
238   // compute the index of the attribute placement
239   int anIndex;
240   TDF_Label aLab;
241   if (myLab.IsAttribute(TDF_TagSource::GetID())) {
242     TDF_Label aLab = myLab.NewChild(); // already exists a floating attribute, create the next
243     anIndex = aLab.Tag();
244   } else { // put the first floating attribute, quite far from other standard attributes
245     anIndex = int(myAttrs.size()) + 1000;
246     TDF_TagSource::Set(myLab)->Set(anIndex);
247     aLab = myLab.FindChild(anIndex, true);
248   }
249   // store the group ID and the attribute ID (to restore correctly)
250   TDataStd_Name::Set(aLab, kGroupAttributeGroupID, theGroup.c_str());
251   TDataStd_Name::Set(aLab, kGroupAttributeID, theID.c_str());
252
253   return addAttribute(theGroup + "__" + theID, theAttrType, anIndex);
254 }
255
256 void Model_Data::allGroups(std::list<std::string>& theGroups)
257 {
258   std::set<std::string> alreadyThere;
259   for(TDF_ChildIDIterator aGroup(myLab, kGroupAttributeGroupID); aGroup.More(); aGroup.Next()) {
260     Handle(TDataStd_Name) aGroupAttr = Handle(TDataStd_Name)::DownCast(aGroup.Value());
261     std::string aGroupID = TCollection_AsciiString(aGroupAttr->Get()).ToCString();
262     if (alreadyThere.find(aGroupID) == alreadyThere.end()) {
263       theGroups.push_back(aGroupID);
264       alreadyThere.insert(aGroupID);
265     }
266   }
267 }
268
269 void Model_Data::attributesOfGroup(const std::string& theGroup,
270   std::list<std::shared_ptr<ModelAPI_Attribute> >& theAttrs)
271 {
272   for(TDF_ChildIDIterator aGroup(myLab, kGroupAttributeGroupID); aGroup.More(); aGroup.Next()) {
273     Handle(TDataStd_Name) aGroupID = Handle(TDataStd_Name)::DownCast(aGroup.Value());
274     if (aGroupID->Get().IsEqual(theGroup.c_str())) {
275       Handle(TDataStd_Name) anID;
276       if (aGroup.Value()->Label().FindAttribute(kGroupAttributeID, anID)) {
277         TCollection_AsciiString anAsciiID(aGroupID->Get() + "__" + anID->Get());
278         theAttrs.push_back(attribute(anAsciiID.ToCString()));
279       }
280     }
281   }
282 }
283
284 void Model_Data::removeAttributes(const std::string& theGroup)
285 {
286   TDF_LabelList aLabsToRemove; // collect labels that must be erased after the cycle
287   for(TDF_ChildIDIterator aGroup(myLab, kGroupAttributeGroupID); aGroup.More(); aGroup.Next()) {
288     Handle(TDataStd_Name) aGroupID = Handle(TDataStd_Name)::DownCast(aGroup.Value());
289     if (aGroupID->Get().IsEqual(theGroup.c_str())) {
290       Handle(TDataStd_Name) anID;
291       if (aGroup.Value()->Label().FindAttribute(kGroupAttributeID, anID)) {
292         TCollection_AsciiString anAsciiID(aGroupID->Get() + "__" + anID->Get());
293         myAttrs.erase(anAsciiID.ToCString());
294         aLabsToRemove.Append(aGroup.Value()->Label());
295       }
296     }
297   }
298   for(TDF_LabelList::Iterator aLab(aLabsToRemove); aLab.More(); aLab.Next()) {
299     aLab.ChangeValue().ForgetAllAttributes(true);
300   }
301 }
302
303
304 // macro for the generic returning of the attribute by the ID
305 #define GET_ATTRIBUTE_BY_ID(ATTR_TYPE, METHOD_NAME) \
306   std::shared_ptr<ATTR_TYPE> Model_Data::METHOD_NAME(const std::string& theID) { \
307     std::shared_ptr<ATTR_TYPE> aRes; \
308     AttributeMap::iterator aFound = myAttrs.find(theID); \
309     if (aFound != myAttrs.end()) { \
310       aRes = std::dynamic_pointer_cast<ATTR_TYPE>(aFound->second.first); \
311     } \
312     return aRes; \
313   }
314 // implement nice getting methods for all ModelAPI attributes
315 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeDocRef, document);
316 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeDouble, real);
317 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeInteger, integer);
318 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeBoolean, boolean);
319 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeString, string);
320 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeStringArray, stringArray);
321 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeReference, reference);
322 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeSelection, selection);
323 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeSelectionList, selectionList);
324 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeRefAttr, refattr);
325 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeRefList, reflist);
326 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeRefAttrList, refattrlist);
327 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeIntArray, intArray);
328 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeDoubleArray, realArray);
329 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeTables, tables);
330
331 std::shared_ptr<ModelAPI_Attribute> Model_Data::attribute(const std::string& theID)
332 {
333   std::shared_ptr<ModelAPI_Attribute> aResult;
334   if (myAttrs.find(theID) == myAttrs.end())  // no such attribute
335     return aResult;
336   return myAttrs[theID].first;
337 }
338
339 const std::string& Model_Data::id(const std::shared_ptr<ModelAPI_Attribute>& theAttr)
340 {
341   AttributeMap::iterator anAttr = myAttrs.begin();
342   for (; anAttr != myAttrs.end(); anAttr++) {
343     if (anAttr->second.first == theAttr)
344       return anAttr->first;
345   }
346   // not found
347   static std::string anEmpty;
348   return anEmpty;
349 }
350
351 bool Model_Data::isEqual(const std::shared_ptr<ModelAPI_Data>& theData)
352 {
353   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theData);
354   if (aData)
355     return myLab.IsEqual(aData->myLab) == Standard_True ;
356   return false;
357 }
358
359 bool Model_Data::isValid()
360 {
361   return !myLab.IsNull() && myLab.HasAttribute();
362 }
363
364 std::list<std::shared_ptr<ModelAPI_Attribute> > Model_Data::attributes(const std::string& theType)
365 {
366   std::list<std::shared_ptr<ModelAPI_Attribute> > aResult;
367   AttributeMap::iterator anAttrsIter = myAttrs.begin();
368   for (; anAttrsIter != myAttrs.end(); anAttrsIter++) {
369     AttributePtr anAttr = anAttrsIter->second.first;
370     if (theType.empty() || anAttr->attributeType() == theType) {
371       aResult.push_back(anAttr);
372     }
373   }
374   return aResult;
375 }
376
377 std::list<std::string> Model_Data::attributesIDs(const std::string& theType)
378 {
379   std::list<std::string> aResult;
380   AttributeMap::iterator anAttrsIter = myAttrs.begin();
381   for (; anAttrsIter != myAttrs.end(); anAttrsIter++) {
382     AttributePtr anAttr = anAttrsIter->second.first;
383     if (theType.empty() || anAttr->attributeType() == theType) {
384       aResult.push_back(anAttrsIter->first);
385     }
386   }
387   return aResult;
388 }
389
390 void Model_Data::sendAttributeUpdated(ModelAPI_Attribute* theAttr)
391 {
392   theAttr->setInitialized();
393   if (theAttr->isArgument()) {
394     if (mySendAttributeUpdated) {
395       if (myObject) {
396         try {
397             myObject->attributeChanged(theAttr->id());
398         } catch(...) {
399           if (owner().get() && owner()->data().get() && owner()->data()->isValid()) {
400             Events_InfoMessage("Model_Data",
401               "%1 has failed during the update").arg(owner()->data()->name()).send();
402           }
403         }
404         static const Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
405         ModelAPI_EventCreator::get()->sendUpdated(myObject, anEvent);
406       }
407     } else {
408       // to avoid too many duplications do not add the same like the last
409       if (myWasChangedButBlocked.empty() || *(myWasChangedButBlocked.rbegin()) != theAttr)
410         myWasChangedButBlocked.push_back(theAttr);
411     }
412   } else {
413     // trim: need to redisplay
414     if (myObject && theAttr->attributeType() == "Point2D") {
415       static const Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
416       ModelAPI_EventCreator::get()->sendUpdated(myObject, anEvent);
417     }
418   }
419 }
420
421 bool Model_Data::blockSendAttributeUpdated(const bool theBlock, const bool theSendMessage)
422 {
423   bool aWasBlocked = !mySendAttributeUpdated;
424   if (mySendAttributeUpdated == theBlock) {
425     mySendAttributeUpdated = !theBlock;
426     if (mySendAttributeUpdated && !myWasChangedButBlocked.empty()) {
427       // so, now it is ok to send the update signal
428       if (theSendMessage) {
429         // make a copy to avoid iteration on modified list
430         // (may be cleared by attribute changed call)
431         std::list<ModelAPI_Attribute*> aWasChangedButBlocked = myWasChangedButBlocked;
432         myWasChangedButBlocked.clear();
433         std::list<ModelAPI_Attribute*>::iterator aChangedIter = aWasChangedButBlocked.begin();
434         for(; aChangedIter != aWasChangedButBlocked.end(); aChangedIter++) {
435           try {
436             myObject->attributeChanged((*aChangedIter)->id());
437           } catch(...) {
438             if (owner().get() && owner()->data().get() && owner()->data()->isValid()) {
439               Events_InfoMessage("Model_Data",
440                 "%1 has failed during the update").arg(owner()->data()->name()).send();
441             }
442           }
443         }
444         static const Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
445         ModelAPI_EventCreator::get()->sendUpdated(myObject, anEvent);
446       } else {
447         myWasChangedButBlocked.clear();
448       }
449     }
450   }
451   return aWasBlocked;
452 }
453
454 void Model_Data::erase()
455 {
456   if (!myLab.IsNull()) {
457     if (myLab.HasAttribute()) {
458       // remove in order to clear back references in other objects
459       std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
460       referencesToObjects(aRefs);
461       std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator
462         anAttrIter = aRefs.begin();
463       for(; anAttrIter != aRefs.end(); anAttrIter++) {
464         std::list<ObjectPtr>::iterator aReferenced = anAttrIter->second.begin();
465         for(; aReferenced != anAttrIter->second.end(); aReferenced++) {
466           if (aReferenced->get() && (*aReferenced)->data()->isValid()) {
467             std::shared_ptr<Model_Data> aData =
468               std::dynamic_pointer_cast<Model_Data>((*aReferenced)->data());
469             aData->removeBackReference(myAttrs[anAttrIter->first].first);
470           }
471         }
472       }
473     }
474     myAttrs.clear();
475     myLab.ForgetAllAttributes();
476   }
477 }
478
479 // indexes in the state array
480 enum StatesIndexes {
481   STATE_INDEX_STATE = 1, // the state type itself
482   STATE_INDEX_TRANSACTION = 2, // transaction ID
483 };
484
485 /// Returns the label array, initializes it by default values if not exists
486 static Handle(TDataStd_IntegerArray) stateArray(TDF_Label& theLab)
487 {
488   Handle(TDataStd_IntegerArray) aStateArray;
489   if (!theLab.FindAttribute(TDataStd_IntegerArray::GetID(), aStateArray)) {
490     aStateArray = TDataStd_IntegerArray::Set(theLab, 1, 2);
491     aStateArray->SetValue(STATE_INDEX_STATE, ModelAPI_StateMustBeUpdated); // default state
492     aStateArray->SetValue(STATE_INDEX_TRANSACTION, 0); // default transaction ID (not existing)
493   }
494   return aStateArray;
495 }
496
497 void Model_Data::execState(const ModelAPI_ExecState theState)
498 {
499   if (theState != ModelAPI_StateNothing) {
500     if (stateArray(myLab)->Value(STATE_INDEX_STATE) != (int)theState) {
501       stateArray(myLab)->SetValue(STATE_INDEX_STATE, (int)theState);
502     }
503   }
504 }
505
506 ModelAPI_ExecState Model_Data::execState()
507 {
508   return ModelAPI_ExecState(stateArray(myLab)->Value(STATE_INDEX_STATE));
509 }
510
511 int Model_Data::updateID()
512 {
513   return stateArray(myLab)->Value(STATE_INDEX_TRANSACTION);
514 }
515
516 void Model_Data::setUpdateID(const int theID)
517 {
518   stateArray(myLab)->SetValue(STATE_INDEX_TRANSACTION, theID);
519 }
520
521 void Model_Data::setError(const std::string& theError, bool theSend)
522 {
523   execState(ModelAPI_StateExecFailed);
524   if (theSend) {
525     Events_InfoMessage("Model_Data", theError).send();
526   }
527   TDataStd_AsciiString::Set(myLab, theError.c_str());
528 }
529
530 void Model_Data::eraseErrorString()
531 {
532   myLab.ForgetAttribute(TDataStd_AsciiString::GetID());
533 }
534
535 std::string Model_Data::error() const
536 {
537   Handle(TDataStd_AsciiString) anErrorAttr;
538   if (myLab.FindAttribute(TDataStd_AsciiString::GetID(), anErrorAttr)) {
539     return std::string(anErrorAttr->Get().ToCString());
540   }
541   return std::string();
542 }
543
544 int Model_Data::featureId() const
545 {
546   return myLab.Father().Tag(); // tag of the feature label
547 }
548
549 void Model_Data::removeBackReference(ObjectPtr theObject, std::string theAttrID)
550 {
551   AttributePtr anAttribute = theObject->data()->attribute(theAttrID);
552   removeBackReference(anAttribute);
553 }
554
555 void Model_Data::removeBackReference(AttributePtr theAttr)
556 {
557   if (myRefsToMe.find(theAttr) == myRefsToMe.end())
558     return;
559
560   myRefsToMe.erase(theAttr);
561
562   // remove concealment immediately: on deselection it must be possible to reselect in GUI the same
563   FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(theAttr->owner());
564   if (aFeatureOwner.get() &&
565     ModelAPI_Session::get()->validators()->isConcealed(aFeatureOwner->getKind(), theAttr->id())) {
566     updateConcealmentFlag();
567   }
568 }
569
570 void Model_Data::addBackReference(FeaturePtr theFeature, std::string theAttrID,
571    const bool theApplyConcealment)
572 {
573   addBackReference(ObjectPtr(theFeature), theAttrID);
574
575   if (theApplyConcealment &&  theFeature->isStable() &&
576       ModelAPI_Session::get()->validators()->isConcealed(theFeature->getKind(), theAttrID)) {
577     std::shared_ptr<ModelAPI_Result> aRes = std::dynamic_pointer_cast<ModelAPI_Result>(myObject);
578     // the second condition is for history upper than concealment causer, so the feature result may
579     // be displayed and previewed; also for avoiding of quick show/hide on history
580     // moving deep down
581     if (aRes && !theFeature->isDisabled()) {
582       aRes->setIsConcealed(true);
583     }
584   }
585 }
586
587 void Model_Data::addBackReference(ObjectPtr theObject, std::string theAttrID)
588 {
589   // it is possible to add the same attribute twice: may be last time the owner was not Stable...
590   AttributePtr anAttribute = theObject->data()->attribute(theAttrID);
591   if (myRefsToMe.find(anAttribute) == myRefsToMe.end())
592     myRefsToMe.insert(anAttribute);
593 }
594
595 void Model_Data::updateConcealmentFlag()
596 {
597   std::set<AttributePtr>::iterator aRefsIter = myRefsToMe.begin();
598   for(; aRefsIter != myRefsToMe.end(); aRefsIter++) {
599     if (aRefsIter->get()) {
600       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefsIter)->owner());
601       if (aFeature.get() && !aFeature->isDisabled() && aFeature->isStable()) {
602         if (ModelAPI_Session::get()->validators()->isConcealed(
603               aFeature->getKind(), (*aRefsIter)->id())) {
604           std::shared_ptr<ModelAPI_Result> aRes =
605             std::dynamic_pointer_cast<ModelAPI_Result>(myObject);
606           if (aRes.get()) {
607             aRes->setIsConcealed(true); // set concealed
608             return;
609           }
610         }
611       }
612     }
613   }
614   std::shared_ptr<ModelAPI_Result> aRes =
615     std::dynamic_pointer_cast<ModelAPI_Result>(myObject);
616   if (aRes.get()) {
617     aRes->setIsConcealed(false);
618   }
619 }
620
621 std::set<std::string> set_union(const std::set<std::string>& theLeft,
622                                 const std::set<std::string>& theRight)
623 {
624   std::set<std::string> aResult;
625   aResult.insert(theLeft.begin(), theLeft.end());
626   aResult.insert(theRight.begin(), theRight.end());
627   return aResult;
628 }
629
630 std::set<std::string> usedParameters(const AttributePointPtr& theAttribute)
631 {
632   std::set<std::string> anUsedParameters;
633   for (int aComponent = 0; aComponent < 3; ++aComponent)
634     anUsedParameters = set_union(anUsedParameters, theAttribute->usedParameters(aComponent));
635   return anUsedParameters;
636 }
637
638 std::set<std::string> usedParameters(const AttributePoint2DPtr& theAttribute)
639 {
640   std::set<std::string> anUsedParameters;
641   for (int aComponent = 0; aComponent < 2; ++aComponent)
642     anUsedParameters = set_union(anUsedParameters, theAttribute->usedParameters(aComponent));
643   return anUsedParameters;
644 }
645
646 std::list<ResultParameterPtr> findVariables(const std::set<std::string>& theParameters,
647                                             const DocumentPtr& theDocument)
648 {
649   std::list<ResultParameterPtr> aResult;
650   std::set<std::string>::const_iterator aParamIt = theParameters.cbegin();
651   for (; aParamIt != theParameters.cend(); ++aParamIt) {
652     const std::string& aName = *aParamIt;
653     double aValue;
654     ResultParameterPtr aParam;
655     // theSearcher is not needed here: in expressions
656     // of features the parameters history is not needed
657     if (ModelAPI_Tools::findVariable(FeaturePtr(), aName, aValue, aParam, theDocument))
658       aResult.push_back(aParam);
659   }
660   return aResult;
661 }
662
663 void Model_Data::referencesToObjects(
664   std::list<std::pair<std::string, std::list<ObjectPtr> > >& theRefs)
665 {
666   static Model_ValidatorsFactory* aValidators =
667     static_cast<Model_ValidatorsFactory*>(ModelAPI_Session::get()->validators());
668   FeaturePtr aMyFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(myObject);
669
670   AttributeMap::iterator anAttrIt = myAttrs.begin();
671   std::list<ObjectPtr> aReferenced; // not inside of cycle to avoid excess memory management
672   for(; anAttrIt != myAttrs.end(); anAttrIt++) {
673     AttributePtr anAttr = anAttrIt->second.first;
674     // skip not-case attributes, that really may refer to anything not-used (issue 671)
675     if (aMyFeature.get() && !aValidators->isCase(aMyFeature, anAttr->id()))
676       continue;
677
678     std::string aType = anAttr->attributeType();
679     if (aType == ModelAPI_AttributeReference::typeId()) { // reference to object
680       std::shared_ptr<ModelAPI_AttributeReference> aRef = std::dynamic_pointer_cast<
681           ModelAPI_AttributeReference>(anAttr);
682       aReferenced.push_back(aRef->value());
683     } else if (aType == ModelAPI_AttributeRefAttr::typeId()) { // reference to attribute or object
684       std::shared_ptr<ModelAPI_AttributeRefAttr> aRef = std::dynamic_pointer_cast<
685           ModelAPI_AttributeRefAttr>(anAttr);
686       if (aRef->isObject()) {
687         aReferenced.push_back(aRef->object());
688       } else {
689         AttributePtr anAttr = aRef->attr();
690         if (anAttr.get())
691           aReferenced.push_back(anAttr->owner());
692       }
693     } else if (aType == ModelAPI_AttributeRefList::typeId()) { // list of references
694       aReferenced = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(anAttr)->list();
695     }
696     else if (aType == ModelAPI_AttributeSelection::typeId()) { // selection attribute
697       std::shared_ptr<ModelAPI_AttributeSelection> aRef = std::dynamic_pointer_cast<
698         ModelAPI_AttributeSelection>(anAttr);
699       FeaturePtr aRefFeat = aRef->contextFeature();
700       if (aRefFeat.get()) { // reference to all results of the referenced feature
701         const std::list<ResultPtr>& allRes = aRefFeat->results();
702         std::list<ResultPtr>::const_iterator aRefRes = allRes.cbegin();
703         for(; aRefRes != allRes.cend(); aRefRes++) {
704           aReferenced.push_back(*aRefRes);
705         }
706       } else {
707         aReferenced.push_back(aRef->context());
708       }
709     } else if (aType == ModelAPI_AttributeSelectionList::typeId()) { // list of selection attributes
710       std::shared_ptr<ModelAPI_AttributeSelectionList> aRef = std::dynamic_pointer_cast<
711           ModelAPI_AttributeSelectionList>(anAttr);
712       for(int a = 0, aSize = aRef->size(); a < aSize; ++a) {
713         FeaturePtr aRefFeat = aRef->value(a)->contextFeature();
714         if (aRefFeat.get()) { // reference to all results of the referenced feature
715           const std::list<ResultPtr>& allRes = aRefFeat->results();
716           std::list<ResultPtr>::const_iterator aRefRes = allRes.cbegin();
717           for (; aRefRes != allRes.cend(); aRefRes++) {
718             aReferenced.push_back(*aRefRes);
719           }
720         } else {
721           aReferenced.push_back(aRef->value(a)->context());
722         }
723       }
724     } else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
725       std::shared_ptr<ModelAPI_AttributeRefAttrList> aRefAttr = std::dynamic_pointer_cast<
726           ModelAPI_AttributeRefAttrList>(anAttr);
727       std::list<std::pair<ObjectPtr, AttributePtr> > aRefs = aRefAttr->list();
728       std::list<std::pair<ObjectPtr, AttributePtr> >::const_iterator anIt = aRefs.begin(),
729                                                                      aLast = aRefs.end();
730       for (; anIt != aLast; anIt++) {
731         aReferenced.push_back(anIt->first);
732       }
733     } else if (aType == ModelAPI_AttributeInteger::typeId()) { // integer attribute
734       AttributeIntegerPtr anAttribute =
735           std::dynamic_pointer_cast<ModelAPI_AttributeInteger>(anAttr);
736       std::set<std::string> anUsedParameters = anAttribute->usedParameters();
737       std::list<ResultParameterPtr> aParameters =
738         findVariables(anUsedParameters, owner()->document());
739       aReferenced.insert(aReferenced.end(), aParameters.begin(), aParameters.end());
740     } else if (aType == ModelAPI_AttributeDouble::typeId()) { // double attribute
741       AttributeDoublePtr anAttribute =
742           std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(anAttr);
743       std::set<std::string> anUsedParameters = anAttribute->usedParameters();
744       std::list<ResultParameterPtr> aParameters =
745         findVariables(anUsedParameters, owner()->document());
746       aReferenced.insert(aReferenced.end(), aParameters.begin(), aParameters.end());
747     } else if (aType == GeomDataAPI_Point::typeId()) { // point attribute
748       AttributePointPtr anAttribute =
749         std::dynamic_pointer_cast<GeomDataAPI_Point>(anAttr);
750       std::set<std::string> anUsedParameters = usedParameters(anAttribute);
751       std::list<ResultParameterPtr> aParameters =
752         findVariables(anUsedParameters, owner()->document());
753       aReferenced.insert(aReferenced.end(), aParameters.begin(), aParameters.end());
754     } else if (aType == GeomDataAPI_Point2D::typeId()) { // point attribute
755       AttributePoint2DPtr anAttribute =
756         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttr);
757       std::set<std::string> anUsedParameters = usedParameters(anAttribute);
758       std::list<ResultParameterPtr> aParameters =
759         findVariables(anUsedParameters, owner()->document());
760       aReferenced.insert(aReferenced.end(), aParameters.begin(), aParameters.end());
761     } else
762       continue; // nothing to do, not reference
763
764     if (!aReferenced.empty()) {
765       theRefs.push_back(
766           std::pair<std::string, std::list<ObjectPtr> >(anAttrIt->first, aReferenced));
767       aReferenced.clear();
768     }
769   }
770 }
771
772 /// makes copy of all attributes on the given label and all sub-labels
773 static void copyAttrs(TDF_Label theSource, TDF_Label theDestination) {
774   TDF_AttributeIterator anAttrIter(theSource);
775   for(; anAttrIter.More(); anAttrIter.Next()) {
776     Handle(TDF_Attribute) aTargetAttr;
777     if (!theDestination.FindAttribute(anAttrIter.Value()->ID(), aTargetAttr)) {
778       // create a new attribute if not yet exists in the destination
779             aTargetAttr = anAttrIter.Value()->NewEmpty();
780       theDestination.AddAttribute(aTargetAttr);
781     }
782     // no special relocation, empty map, but self-relocation is on: copy references w/o changes
783     Handle(TDF_RelocationTable) aRelocTable = new TDF_RelocationTable(Standard_True);
784     anAttrIter.Value()->Paste(aTargetAttr, aRelocTable);
785   }
786   // copy the sub-labels content
787   TDF_ChildIterator aSubLabsIter(theSource);
788   for(; aSubLabsIter.More(); aSubLabsIter.Next()) {
789     copyAttrs(aSubLabsIter.Value(), theDestination.FindChild(aSubLabsIter.Value().Tag()));
790   }
791 }
792
793 void Model_Data::copyTo(std::shared_ptr<ModelAPI_Data> theTarget)
794 {
795   TDF_Label aTargetRoot = std::dynamic_pointer_cast<Model_Data>(theTarget)->label();
796   copyAttrs(myLab, aTargetRoot);
797   // reinitialize Model_Attributes by TDF_Attributes set
798   std::shared_ptr<Model_Data> aTData = std::dynamic_pointer_cast<Model_Data>(theTarget);
799   aTData->myAttrs.clear();
800   theTarget->owner()->initAttributes(); // reinitialize feature attributes
801 }
802
803 bool Model_Data::isInHistory()
804 {
805   return myFlags->Value(kFlagInHistory) == Standard_True;
806 }
807
808 void Model_Data::setIsInHistory(const bool theFlag)
809 {
810   return myFlags->SetValue(kFlagInHistory, theFlag);
811 }
812
813 bool Model_Data::isDeleted()
814 {
815   return myFlags->Value(kFlagDeleted) == Standard_True;
816 }
817
818 void Model_Data::setIsDeleted(const bool theFlag)
819 {
820   return myFlags->SetValue(kFlagDeleted, theFlag);
821 }
822
823 bool Model_Data::isDisplayed()
824 {
825   if (!myObject.get() || !myObject->document().get() || // object is in valid
826       myFlags->Value(kFlagDisplayed) != Standard_True) // or it was not displayed before
827     return false;
828   if (myObject->document()->isActive()) // for active documents it must be ok anyway
829     return true;
830   // any object from the root document except part result may be displayed
831   if (myObject->document() == ModelAPI_Session::get()->moduleDocument() &&
832       myObject->groupName() != ModelAPI_ResultPart::group())
833     return true;
834   return false;
835 }
836
837 void Model_Data::setDisplayed(const bool theDisplay)
838 {
839   if (theDisplay != isDisplayed()) {
840     myFlags->SetValue(kFlagDisplayed, theDisplay);
841     static Events_Loop* aLoop = Events_Loop::loop();
842     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
843     static const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
844     aECreator->sendUpdated(myObject, EVENT_DISP);
845   }
846 }
847
848 std::shared_ptr<ModelAPI_Data> Model_Data::invalidPtr()
849 {
850   return kInvalid;
851 }
852
853 std::shared_ptr<ModelAPI_Data> Model_Data::invalidData()
854 {
855   return kInvalid;
856 }
857
858 std::shared_ptr<ModelAPI_Object> Model_Data::owner()
859 {
860   return myObject;
861 }
862
863 bool Model_Data::isPrecedingAttribute(const std::string& theAttribute1,
864                                       const std::string& theAttribute2) const
865 {
866   AttributeMap::const_iterator aFound1 = myAttrs.find(theAttribute1);
867   AttributeMap::const_iterator aFound2 = myAttrs.find(theAttribute2);
868   if (aFound2 == myAttrs.end())
869     return true;
870   else if (aFound1 == myAttrs.end())
871     return false;
872   return aFound1->second.second < aFound2->second.second;
873 }