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