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