Salome HOME
Task 2.1. Management of result names
[modules/shaper.git] / src / Model / Model_Data.cpp
1 // Copyright (C) 2014-2017  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
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include <Model_Data.h>
22 #include <Model_AttributeDocRef.h>
23 #include <Model_AttributeInteger.h>
24 #include <Model_AttributeDouble.h>
25 #include <Model_AttributeDoubleArray.h>
26 #include <Model_AttributeReference.h>
27 #include <Model_AttributeRefAttr.h>
28 #include <Model_AttributeRefList.h>
29 #include <Model_AttributeRefAttrList.h>
30 #include <Model_AttributeBoolean.h>
31 #include <Model_AttributeString.h>
32 #include <Model_AttributeStringArray.h>
33 #include <Model_AttributeSelection.h>
34 #include <Model_AttributeSelectionList.h>
35 #include <Model_AttributeIntArray.h>
36 #include <Model_AttributeTables.h>
37 #include <Model_Events.h>
38 #include <Model_Expression.h>
39 #include <ModelAPI_Feature.h>
40 #include <ModelAPI_Result.h>
41 #include <ModelAPI_ResultParameter.h>
42 #include <ModelAPI_Validator.h>
43 #include <ModelAPI_Session.h>
44 #include <ModelAPI_ResultPart.h>
45 #include <ModelAPI_ResultCompSolid.h>
46 #include <ModelAPI_Tools.h>
47 #include <Model_Validator.h>
48
49 #include <GeomDataAPI_Point.h>
50 #include <GeomDataAPI_Point2D.h>
51
52 #include <GeomData_Point.h>
53 #include <GeomData_Point2D.h>
54 #include <GeomData_Dir.h>
55 #include <Events_Loop.h>
56 #include <Events_InfoMessage.h>
57
58 #include <TDataStd_Name.hxx>
59 #include <TDataStd_AsciiString.hxx>
60 #include <TDataStd_IntegerArray.hxx>
61 #include <TDF_AttributeIterator.hxx>
62 #include <TDF_ChildIterator.hxx>
63 #include <TDF_RelocationTable.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
79 // invalid data
80 const static std::shared_ptr<ModelAPI_Data> kInvalid(new Model_Data());
81
82 Model_Data::Model_Data() : mySendAttributeUpdated(true), myWasChangedButBlocked(false)
83 {
84 }
85
86 void Model_Data::setLabel(TDF_Label theLab)
87 {
88   myLab = theLab;
89   // set or get the default flags
90   if (!myLab.FindAttribute(TDataStd_BooleanArray::GetID(), myFlags)) {
91     // set default values if not found
92     myFlags = TDataStd_BooleanArray::Set(myLab, 0, 2);
93     myFlags->SetValue(kFlagInHistory, Standard_True); // is in history by default is true
94     myFlags->SetValue(kFlagDisplayed, Standard_True); // is displayed by default is true
95     myFlags->SetValue(kFlagDeleted, Standard_False); // is deleted by default is false
96   } else if (myFlags->Length() != 3) { // for old formats support
97     Standard_Boolean aFlag0 = myFlags->Upper() >= 0 ? myFlags->Value(0) : Standard_True;
98     Standard_Boolean aFlag1 = myFlags->Upper() >= 1 ? myFlags->Value(1) : Standard_True;
99     Standard_Boolean aFlag2 = myFlags->Upper() >= 2 ? myFlags->Value(2) : Standard_True;
100     Handle(TColStd_HArray1OfByte) aNewArray = new TColStd_HArray1OfByte(0, 2);
101     myFlags->SetInternalArray(aNewArray);
102     myFlags->SetValue(0, aFlag0);
103     myFlags->SetValue(1, aFlag1);
104     myFlags->SetValue(2, aFlag2);
105   }
106 }
107
108 std::string Model_Data::name()
109 {
110   Handle(TDataStd_Name) aName;
111   if (myLab.FindAttribute(TDataStd_Name::GetID(), aName)) {
112 #ifdef DEBUG_NAMES
113     myObject->myName = TCollection_AsciiString(aName->Get()).ToCString();
114 #endif
115     return std::string(TCollection_AsciiString(aName->Get()).ToCString());
116   }
117   return "";  // not defined
118 }
119
120 void Model_Data::setName(const std::string& theName)
121 {
122   bool isModified = false;
123   std::string anOldName = name();
124   Handle(TDataStd_Name) aName;
125   if (!myLab.FindAttribute(TDataStd_Name::GetID(), aName)) {
126     TDataStd_Name::Set(myLab, theName.c_str());
127     isModified = true;
128   } else {
129     isModified = !aName->Get().IsEqual(theName.c_str());
130     if (isModified)
131       aName->Set(theName.c_str());
132   }
133   if (mySendAttributeUpdated && isModified)
134     ModelAPI_ObjectRenamedMessage::send(myObject, anOldName, theName, this);
135   if (isModified && myObject && myObject->document()) {
136     std::dynamic_pointer_cast<Model_Document>(myObject->document())->
137       changeNamingName(anOldName, theName, myLab);
138   }
139 #ifdef DEBUG_NAMES
140   myObject->myName = theName;
141 #endif
142 }
143
144 AttributePtr Model_Data::addAttribute(const std::string& theID, const std::string theAttrType)
145 {
146   AttributePtr aResult;
147   int anAttrIndex = int(myAttrs.size()) + 1;
148   TDF_Label anAttrLab = myLab.FindChild(anAttrIndex);
149   ModelAPI_Attribute* anAttr = 0;
150   if (theAttrType == ModelAPI_AttributeDocRef::typeId()) {
151     anAttr = new Model_AttributeDocRef(anAttrLab);
152   } else if (theAttrType == Model_AttributeInteger::typeId()) {
153     anAttr = new Model_AttributeInteger(anAttrLab);
154   } else if (theAttrType == ModelAPI_AttributeDouble::typeId()) {
155     anAttr = new Model_AttributeDouble(anAttrLab);
156   } else if (theAttrType == Model_AttributeBoolean::typeId()) {
157     anAttr = new Model_AttributeBoolean(anAttrLab);
158   } else if (theAttrType == Model_AttributeString::typeId()) {
159     anAttr = new Model_AttributeString(anAttrLab);
160   } else if (theAttrType == Model_AttributeStringArray::typeId()) {
161     anAttr = new Model_AttributeStringArray(anAttrLab);
162   } else if (theAttrType == ModelAPI_AttributeReference::typeId()) {
163     anAttr = new Model_AttributeReference(anAttrLab);
164   } else if (theAttrType == ModelAPI_AttributeSelection::typeId()) {
165     anAttr = new Model_AttributeSelection(anAttrLab);
166   } else if (theAttrType == ModelAPI_AttributeSelectionList::typeId()) {
167     anAttr = new Model_AttributeSelectionList(anAttrLab);
168   } else if (theAttrType == ModelAPI_AttributeRefAttr::typeId()) {
169     anAttr = new Model_AttributeRefAttr(anAttrLab);
170   } else if (theAttrType == ModelAPI_AttributeRefList::typeId()) {
171     anAttr = new Model_AttributeRefList(anAttrLab);
172   } else if (theAttrType == ModelAPI_AttributeRefAttrList::typeId()) {
173     anAttr = new Model_AttributeRefAttrList(anAttrLab);
174   } else if (theAttrType == ModelAPI_AttributeIntArray::typeId()) {
175     anAttr = new Model_AttributeIntArray(anAttrLab);
176   } else if (theAttrType == ModelAPI_AttributeDoubleArray::typeId()) {
177     anAttr = new Model_AttributeDoubleArray(anAttrLab);
178   } else if (theAttrType == ModelAPI_AttributeTables::typeId()) {
179     anAttr = new Model_AttributeTables(anAttrLab);
180   }
181   // create also GeomData attributes here because only here the OCAF structure is known
182   else if (theAttrType == GeomData_Point::typeId()) {
183     GeomData_Point* anAttribute = new GeomData_Point();
184     bool anAllInitialized = true;
185     for (int aComponent = 0; aComponent < GeomData_Point::NUM_COMPONENTS; ++aComponent) {
186       TDF_Label anExpressionLab = anAttrLab.FindChild(aComponent + 1);
187       anAttribute->myExpression[aComponent].reset(new Model_ExpressionDouble(anExpressionLab));
188       anAllInitialized = anAllInitialized && anAttribute->myExpression[aComponent]->isInitialized();
189     }
190     anAttribute->myIsInitialized = anAllInitialized;
191     anAttr = anAttribute;
192   } else if (theAttrType == GeomData_Dir::typeId()) {
193     anAttr = new GeomData_Dir(anAttrLab);
194   } else if (theAttrType == GeomData_Point2D::typeId()) {
195     GeomData_Point2D* anAttribute = new GeomData_Point2D();
196     bool anAllInitialized = true;
197     for (int aComponent = 0; aComponent < GeomData_Point2D::NUM_COMPONENTS; ++aComponent) {
198       TDF_Label anExpressionLab = anAttrLab.FindChild(aComponent + 1);
199       anAttribute->myExpression[aComponent].reset(new Model_ExpressionDouble(anExpressionLab));
200       anAllInitialized = anAllInitialized && anAttribute->myExpression[aComponent]->isInitialized();
201     }
202     anAttribute->myIsInitialized = anAllInitialized;
203     anAttr = anAttribute;
204   }
205   if (anAttr) {
206     aResult = std::shared_ptr<ModelAPI_Attribute>(anAttr);
207     myAttrs[theID] = std::pair<AttributePtr, int>(aResult, anAttrIndex);
208     anAttr->setObject(myObject);
209     anAttr->setID(theID);
210   } else {
211     Events_InfoMessage("Model_Data",
212       "Can not create unknown type of attribute %1").arg(theAttrType).send();
213   }
214   return aResult;
215 }
216
217 // macro for the generic returning of the attribute by the ID
218 #define GET_ATTRIBUTE_BY_ID(ATTR_TYPE, METHOD_NAME) \
219   std::shared_ptr<ATTR_TYPE> Model_Data::METHOD_NAME(const std::string& theID) { \
220     std::shared_ptr<ATTR_TYPE> aRes; \
221     AttributeMap::iterator aFound = myAttrs.find(theID); \
222     if (aFound != myAttrs.end()) { \
223       aRes = std::dynamic_pointer_cast<ATTR_TYPE>(aFound->second.first); \
224     } \
225     return aRes; \
226   }
227 // implement nice getting methods for all ModelAPI attributes
228 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeDocRef, document);
229 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeDouble, real);
230 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeInteger, integer);
231 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeBoolean, boolean);
232 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeString, string);
233 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeStringArray, stringArray);
234 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeReference, reference);
235 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeSelection, selection);
236 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeSelectionList, selectionList);
237 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeRefAttr, refattr);
238 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeRefList, reflist);
239 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeRefAttrList, refattrlist);
240 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeIntArray, intArray);
241 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeDoubleArray, realArray);
242 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeTables, tables);
243
244 std::shared_ptr<ModelAPI_Attribute> Model_Data::attribute(const std::string& theID)
245 {
246   std::shared_ptr<ModelAPI_Attribute> aResult;
247   if (myAttrs.find(theID) == myAttrs.end())  // no such attribute
248     return aResult;
249   return myAttrs[theID].first;
250 }
251
252 const std::string& Model_Data::id(const std::shared_ptr<ModelAPI_Attribute>& theAttr)
253 {
254   AttributeMap::iterator anAttr = myAttrs.begin();
255   for (; anAttr != myAttrs.end(); anAttr++) {
256     if (anAttr->second.first == theAttr)
257       return anAttr->first;
258   }
259   // not found
260   static std::string anEmpty;
261   return anEmpty;
262 }
263
264 bool Model_Data::isEqual(const std::shared_ptr<ModelAPI_Data>& theData)
265 {
266   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theData);
267   if (aData)
268     return myLab.IsEqual(aData->myLab) == Standard_True ;
269   return false;
270 }
271
272 bool Model_Data::isValid()
273 {
274   return !myLab.IsNull() && myLab.HasAttribute();
275 }
276
277 std::list<std::shared_ptr<ModelAPI_Attribute> > Model_Data::attributes(const std::string& theType)
278 {
279   std::list<std::shared_ptr<ModelAPI_Attribute> > aResult;
280   AttributeMap::iterator anAttrsIter = myAttrs.begin();
281   for (; anAttrsIter != myAttrs.end(); anAttrsIter++) {
282     AttributePtr anAttr = anAttrsIter->second.first;
283     if (theType.empty() || anAttr->attributeType() == theType) {
284       aResult.push_back(anAttr);
285     }
286   }
287   return aResult;
288 }
289
290 std::list<std::string> Model_Data::attributesIDs(const std::string& theType)
291 {
292   std::list<std::string> aResult;
293   AttributeMap::iterator anAttrsIter = myAttrs.begin();
294   for (; anAttrsIter != myAttrs.end(); anAttrsIter++) {
295     AttributePtr anAttr = anAttrsIter->second.first;
296     if (theType.empty() || anAttr->attributeType() == theType) {
297       aResult.push_back(anAttrsIter->first);
298     }
299   }
300   return aResult;
301 }
302
303 void Model_Data::sendAttributeUpdated(ModelAPI_Attribute* theAttr)
304 {
305   theAttr->setInitialized();
306   if (theAttr->isArgument()) {
307     if (mySendAttributeUpdated) {
308       if (myObject) {
309         try {
310             myObject->attributeChanged(theAttr->id());
311         } catch(...) {
312           if (owner().get() && owner()->data().get() && owner()->data()->isValid()) {
313             Events_InfoMessage("Model_Data",
314               "%1 has failed during the update").arg(owner()->data()->name()).send();
315           }
316         }
317         static const Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
318         ModelAPI_EventCreator::get()->sendUpdated(myObject, anEvent);
319       }
320     } else {
321       // to avoid too many duplications do not add the same like the last
322       if (myWasChangedButBlocked.empty() || *(myWasChangedButBlocked.rbegin()) != theAttr)
323         myWasChangedButBlocked.push_back(theAttr);
324     }
325   } else {
326     // trim: need to redisplay
327     if (myObject) {
328       static const Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
329       ModelAPI_EventCreator::get()->sendUpdated(myObject, anEvent);
330     }
331   }
332 }
333
334 bool Model_Data::blockSendAttributeUpdated(const bool theBlock, const bool theSendMessage)
335 {
336   bool aWasBlocked = !mySendAttributeUpdated;
337   if (mySendAttributeUpdated == theBlock) {
338     mySendAttributeUpdated = !theBlock;
339     if (mySendAttributeUpdated && !myWasChangedButBlocked.empty()) {
340       // so, now it is ok to send the update signal
341       if (theSendMessage) {
342         // make a copy to avoid iteration on modified list
343         // (may be cleared by attribute changed call)
344         std::list<ModelAPI_Attribute*> aWasChangedButBlocked = myWasChangedButBlocked;
345         myWasChangedButBlocked.clear();
346         std::list<ModelAPI_Attribute*>::iterator aChangedIter = aWasChangedButBlocked.begin();
347         for(; aChangedIter != aWasChangedButBlocked.end(); aChangedIter++) {
348           try {
349             myObject->attributeChanged((*aChangedIter)->id());
350           } catch(...) {
351             if (owner().get() && owner()->data().get() && owner()->data()->isValid()) {
352               Events_InfoMessage("Model_Data",
353                 "%1 has failed during the update").arg(owner()->data()->name()).send();
354             }
355           }
356         }
357         static const Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
358         ModelAPI_EventCreator::get()->sendUpdated(myObject, anEvent);
359       } else {
360         myWasChangedButBlocked.clear();
361       }
362     }
363   }
364   return aWasBlocked;
365 }
366
367 void Model_Data::erase()
368 {
369   if (!myLab.IsNull()) {
370     if (myLab.HasAttribute()) {
371       // remove in order to clear back references in other objects
372       std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
373       referencesToObjects(aRefs);
374       std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator
375         anAttrIter = aRefs.begin();
376       for(; anAttrIter != aRefs.end(); anAttrIter++) {
377         std::list<ObjectPtr>::iterator aReferenced = anAttrIter->second.begin();
378         for(; aReferenced != anAttrIter->second.end(); aReferenced++) {
379           if (aReferenced->get() && (*aReferenced)->data()->isValid()) {
380             std::shared_ptr<Model_Data> aData =
381               std::dynamic_pointer_cast<Model_Data>((*aReferenced)->data());
382             aData->removeBackReference(myAttrs[anAttrIter->first].first);
383           }
384         }
385       }
386     }
387     myAttrs.clear();
388     myLab.ForgetAllAttributes();
389   }
390 }
391
392 // indexes in the state array
393 enum StatesIndexes {
394   STATE_INDEX_STATE = 1, // the state type itself
395   STATE_INDEX_TRANSACTION = 2, // transaction ID
396 };
397
398 /// Returns the label array, initialises it by default values if not exists
399 static Handle(TDataStd_IntegerArray) stateArray(TDF_Label& theLab)
400 {
401   Handle(TDataStd_IntegerArray) aStateArray;
402   if (!theLab.FindAttribute(TDataStd_IntegerArray::GetID(), aStateArray)) {
403     aStateArray = TDataStd_IntegerArray::Set(theLab, 1, 2);
404     aStateArray->SetValue(STATE_INDEX_STATE, ModelAPI_StateMustBeUpdated); // default state
405     aStateArray->SetValue(STATE_INDEX_TRANSACTION, 0); // default transaction ID (not existing)
406   }
407   return aStateArray;
408 }
409
410 void Model_Data::execState(const ModelAPI_ExecState theState)
411 {
412   if (theState != ModelAPI_StateNothing) {
413     if (stateArray(myLab)->Value(STATE_INDEX_STATE) != (int)theState) {
414       stateArray(myLab)->SetValue(STATE_INDEX_STATE, (int)theState);
415     }
416   }
417 }
418
419 ModelAPI_ExecState Model_Data::execState()
420 {
421   return ModelAPI_ExecState(stateArray(myLab)->Value(STATE_INDEX_STATE));
422 }
423
424 int Model_Data::updateID()
425 {
426   return stateArray(myLab)->Value(STATE_INDEX_TRANSACTION);
427 }
428
429 void Model_Data::setUpdateID(const int theID)
430 {
431   stateArray(myLab)->SetValue(STATE_INDEX_TRANSACTION, theID);
432 }
433
434 void Model_Data::setError(const std::string& theError, bool theSend)
435 {
436   execState(ModelAPI_StateExecFailed);
437   if (theSend) {
438     Events_InfoMessage("Model_Data", theError).send();
439   }
440   TDataStd_AsciiString::Set(myLab, theError.c_str());
441 }
442
443 void Model_Data::eraseErrorString()
444 {
445   myLab.ForgetAttribute(TDataStd_AsciiString::GetID());
446 }
447
448 std::string Model_Data::error() const
449 {
450   Handle(TDataStd_AsciiString) anErrorAttr;
451   if (myLab.FindAttribute(TDataStd_AsciiString::GetID(), anErrorAttr)) {
452     return std::string(anErrorAttr->Get().ToCString());
453   }
454   return std::string();
455 }
456
457 int Model_Data::featureId() const
458 {
459   return myLab.Father().Tag(); // tag of the feature label
460 }
461
462 void Model_Data::eraseBackReferences()
463 {
464   myRefsToMe.clear();
465   std::shared_ptr<ModelAPI_Result> aRes =
466     std::dynamic_pointer_cast<ModelAPI_Result>(myObject);
467   if (aRes)
468     aRes->setIsConcealed(false);
469 }
470
471 void Model_Data::removeBackReference(FeaturePtr theFeature, std::string theAttrID)
472 {
473   AttributePtr anAttribute = theFeature->data()->attribute(theAttrID);
474   removeBackReference(anAttribute);
475 }
476
477 void Model_Data::removeBackReference(AttributePtr theAttr)
478 {
479   if (myRefsToMe.find(theAttr) == myRefsToMe.end())
480     return;
481
482   myRefsToMe.erase(theAttr);
483
484   // remove concealment immideately: on deselection it must be posible to reselect in GUI the same
485   FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(theAttr->owner());
486   if (aFeatureOwner.get() &&
487     ModelAPI_Session::get()->validators()->isConcealed(aFeatureOwner->getKind(), theAttr->id())) {
488     updateConcealmentFlag();
489   }
490 }
491
492 void Model_Data::addBackReference(FeaturePtr theFeature, std::string theAttrID,
493    const bool theApplyConcealment)
494 {
495   // it is possible to add the same attribute twice: may be last time the owner was not Stable...
496   AttributePtr anAttribute = theFeature->data()->attribute(theAttrID);
497   if (myRefsToMe.find(anAttribute) == myRefsToMe.end())
498     myRefsToMe.insert(theFeature->data()->attribute(theAttrID));
499
500   if (theApplyConcealment &&  theFeature->isStable() &&
501       ModelAPI_Session::get()->validators()->isConcealed(theFeature->getKind(), theAttrID)) {
502     std::shared_ptr<ModelAPI_Result> aRes =
503       std::dynamic_pointer_cast<ModelAPI_Result>(myObject);
504     // the second condition is for history upper than concealment causer, so the feature result may
505     // be displayed and previewed; also for avoiding of quick show/hide on history
506     // moving deep down
507     if (aRes && !theFeature->isDisabled()) {
508       aRes->setIsConcealed(true);
509     }
510   }
511 }
512
513 void Model_Data::updateConcealmentFlag()
514 {
515   std::set<AttributePtr>::iterator aRefsIter = myRefsToMe.begin();
516   for(; aRefsIter != myRefsToMe.end(); aRefsIter++) {
517     if (aRefsIter->get()) {
518       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefsIter)->owner());
519       if (aFeature.get() && !aFeature->isDisabled() && aFeature->isStable()) {
520         if (ModelAPI_Session::get()->validators()->isConcealed(
521               aFeature->getKind(), (*aRefsIter)->id())) {
522           std::shared_ptr<ModelAPI_Result> aRes =
523             std::dynamic_pointer_cast<ModelAPI_Result>(myObject);
524           if (aRes.get()) {
525             aRes->setIsConcealed(true); // set concealed
526             return;
527           }
528         }
529       }
530     }
531   }
532   std::shared_ptr<ModelAPI_Result> aRes =
533     std::dynamic_pointer_cast<ModelAPI_Result>(myObject);
534   if (aRes.get()) {
535     aRes->setIsConcealed(false);
536   }
537 }
538
539 std::set<std::string> set_union(const std::set<std::string>& theLeft,
540                                 const std::set<std::string>& theRight)
541 {
542   std::set<std::string> aResult;
543   aResult.insert(theLeft.begin(), theLeft.end());
544   aResult.insert(theRight.begin(), theRight.end());
545   return aResult;
546 }
547
548 std::set<std::string> usedParameters(const AttributePointPtr& theAttribute)
549 {
550   std::set<std::string> anUsedParameters;
551   for (int aComponent = 0; aComponent < 3; ++aComponent)
552     anUsedParameters = set_union(anUsedParameters, theAttribute->usedParameters(aComponent));
553   return anUsedParameters;
554 }
555
556 std::set<std::string> usedParameters(const AttributePoint2DPtr& theAttribute)
557 {
558   std::set<std::string> anUsedParameters;
559   for (int aComponent = 0; aComponent < 2; ++aComponent)
560     anUsedParameters = set_union(anUsedParameters, theAttribute->usedParameters(aComponent));
561   return anUsedParameters;
562 }
563
564 std::list<ResultParameterPtr> findVariables(const std::set<std::string>& theParameters)
565 {
566   std::list<ResultParameterPtr> aResult;
567   std::set<std::string>::const_iterator aParamIt = theParameters.cbegin();
568   for (; aParamIt != theParameters.cend(); ++aParamIt) {
569     const std::string& aName = *aParamIt;
570     double aValue;
571     ResultParameterPtr aParam;
572     // theSearcher is not needed here: in expressions
573     // of features the parameters history is not needed
574     if (ModelAPI_Tools::findVariable(FeaturePtr(), aName, aValue, aParam))
575       aResult.push_back(aParam);
576   }
577   return aResult;
578 }
579
580 void Model_Data::referencesToObjects(
581   std::list<std::pair<std::string, std::list<ObjectPtr> > >& theRefs)
582 {
583   static Model_ValidatorsFactory* aValidators =
584     static_cast<Model_ValidatorsFactory*>(ModelAPI_Session::get()->validators());
585   FeaturePtr aMyFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(myObject);
586
587   AttributeMap::iterator anAttrIt = myAttrs.begin();
588   std::list<ObjectPtr> aReferenced; // not inside of cycle to avoid excess memory management
589   for(; anAttrIt != myAttrs.end(); anAttrIt++) {
590     AttributePtr anAttr = anAttrIt->second.first;
591     // skip not-case attributes, that really may refer to anything not-used (issue 671)
592     if (aMyFeature.get() && !aValidators->isCase(aMyFeature, anAttr->id()))
593       continue;
594
595     std::string aType = anAttr->attributeType();
596     if (aType == ModelAPI_AttributeReference::typeId()) { // reference to object
597       std::shared_ptr<ModelAPI_AttributeReference> aRef = std::dynamic_pointer_cast<
598           ModelAPI_AttributeReference>(anAttr);
599       aReferenced.push_back(aRef->value());
600     } else if (aType == ModelAPI_AttributeRefAttr::typeId()) { // reference to attribute or object
601       std::shared_ptr<ModelAPI_AttributeRefAttr> aRef = std::dynamic_pointer_cast<
602           ModelAPI_AttributeRefAttr>(anAttr);
603       if (aRef->isObject()) {
604         aReferenced.push_back(aRef->object());
605       } else {
606         AttributePtr anAttr = aRef->attr();
607         if (anAttr.get())
608           aReferenced.push_back(anAttr->owner());
609       }
610     } else if (aType == ModelAPI_AttributeRefList::typeId()) { // list of references
611       aReferenced = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(anAttr)->list();
612     } else if (aType == ModelAPI_AttributeSelection::typeId()) { // selection attribute
613       std::shared_ptr<ModelAPI_AttributeSelection> aRef = std::dynamic_pointer_cast<
614           ModelAPI_AttributeSelection>(anAttr);
615       aReferenced.push_back(aRef->context());
616     } else if (aType == ModelAPI_AttributeSelectionList::typeId()) { // list of selection attributes
617       std::shared_ptr<ModelAPI_AttributeSelectionList> aRef = std::dynamic_pointer_cast<
618           ModelAPI_AttributeSelectionList>(anAttr);
619       for(int a = 0, aSize = aRef->size(); a < aSize; ++a) {
620         aReferenced.push_back(aRef->value(a)->context());
621       }
622     } else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
623       std::shared_ptr<ModelAPI_AttributeRefAttrList> aRefAttr = std::dynamic_pointer_cast<
624           ModelAPI_AttributeRefAttrList>(anAttr);
625       std::list<std::pair<ObjectPtr, AttributePtr> > aRefs = aRefAttr->list();
626       std::list<std::pair<ObjectPtr, AttributePtr> >::const_iterator anIt = aRefs.begin(),
627                                                                      aLast = aRefs.end();
628       for (; anIt != aLast; anIt++) {
629         aReferenced.push_back(anIt->first);
630       }
631     } else if (aType == ModelAPI_AttributeInteger::typeId()) { // integer attribute
632       AttributeIntegerPtr anAttribute =
633           std::dynamic_pointer_cast<ModelAPI_AttributeInteger>(anAttr);
634       std::set<std::string> anUsedParameters = anAttribute->usedParameters();
635       std::list<ResultParameterPtr> aParameters = findVariables(anUsedParameters);
636       aReferenced.insert(aReferenced.end(), aParameters.begin(), aParameters.end());
637     } else if (aType == ModelAPI_AttributeDouble::typeId()) { // double attribute
638       AttributeDoublePtr anAttribute =
639           std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(anAttr);
640       std::set<std::string> anUsedParameters = anAttribute->usedParameters();
641       std::list<ResultParameterPtr> aParameters = findVariables(anUsedParameters);
642       aReferenced.insert(aReferenced.end(), aParameters.begin(), aParameters.end());
643     } else if (aType == GeomDataAPI_Point::typeId()) { // point attribute
644       AttributePointPtr anAttribute =
645         std::dynamic_pointer_cast<GeomDataAPI_Point>(anAttr);
646       std::set<std::string> anUsedParameters = usedParameters(anAttribute);
647       std::list<ResultParameterPtr> aParameters = findVariables(anUsedParameters);
648       aReferenced.insert(aReferenced.end(), aParameters.begin(), aParameters.end());
649     } else if (aType == GeomDataAPI_Point2D::typeId()) { // point attribute
650       AttributePoint2DPtr anAttribute =
651         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttr);
652       std::set<std::string> anUsedParameters = usedParameters(anAttribute);
653       std::list<ResultParameterPtr> aParameters = findVariables(anUsedParameters);
654       aReferenced.insert(aReferenced.end(), aParameters.begin(), aParameters.end());
655     } else
656       continue; // nothing to do, not reference
657
658     if (!aReferenced.empty()) {
659       theRefs.push_back(
660           std::pair<std::string, std::list<ObjectPtr> >(anAttrIt->first, aReferenced));
661       aReferenced.clear();
662     }
663   }
664 }
665
666 /// makes copy of all attributes on the given label and all sub-labels
667 static void copyAttrs(TDF_Label theSource, TDF_Label theDestination) {
668   TDF_AttributeIterator anAttrIter(theSource);
669   for(; anAttrIter.More(); anAttrIter.Next()) {
670     Handle(TDF_Attribute) aTargetAttr;
671     if (!theDestination.FindAttribute(anAttrIter.Value()->ID(), aTargetAttr)) {
672       // create a new attribute if not yet exists in the destination
673             aTargetAttr = anAttrIter.Value()->NewEmpty();
674       theDestination.AddAttribute(aTargetAttr);
675     }
676     // no special relocation, empty map, but self-relocation is on: copy references w/o changes
677     Handle(TDF_RelocationTable) aRelocTable = new TDF_RelocationTable(Standard_True);
678     anAttrIter.Value()->Paste(aTargetAttr, aRelocTable);
679   }
680   // copy the sub-labels content
681   TDF_ChildIterator aSubLabsIter(theSource);
682   for(; aSubLabsIter.More(); aSubLabsIter.Next()) {
683     copyAttrs(aSubLabsIter.Value(), theDestination.FindChild(aSubLabsIter.Value().Tag()));
684   }
685 }
686
687 void Model_Data::copyTo(std::shared_ptr<ModelAPI_Data> theTarget)
688 {
689   TDF_Label aTargetRoot = std::dynamic_pointer_cast<Model_Data>(theTarget)->label();
690   copyAttrs(myLab, aTargetRoot);
691   // reinitialize Model_Attributes by TDF_Attributes set
692   std::shared_ptr<Model_Data> aTData = std::dynamic_pointer_cast<Model_Data>(theTarget);
693   aTData->myAttrs.clear();
694   theTarget->owner()->initAttributes(); // reinit feature attributes
695 }
696
697 bool Model_Data::isInHistory()
698 {
699   return myFlags->Value(kFlagInHistory) == Standard_True;
700 }
701
702 void Model_Data::setIsInHistory(const bool theFlag)
703 {
704   return myFlags->SetValue(kFlagInHistory, theFlag);
705 }
706
707 bool Model_Data::isDeleted()
708 {
709   return myFlags->Value(kFlagDeleted) == Standard_True;
710 }
711
712 void Model_Data::setIsDeleted(const bool theFlag)
713 {
714   return myFlags->SetValue(kFlagDeleted, theFlag);
715 }
716
717 bool Model_Data::isDisplayed()
718 {
719   if (!myObject.get() || !myObject->document().get() || // object is in valid
720       myFlags->Value(kFlagDisplayed) != Standard_True) // or it was not displayed before
721     return false;
722   if (myObject->document()->isActive()) // for active documents it must be ok anyway
723     return true;
724   // any object from the root document except part result may be displayed
725   if (myObject->document() == ModelAPI_Session::get()->moduleDocument() &&
726       myObject->groupName() != ModelAPI_ResultPart::group())
727     return true;
728   return false;
729 }
730
731 void Model_Data::setDisplayed(const bool theDisplay)
732 {
733   if (theDisplay != isDisplayed()) {
734     myFlags->SetValue(kFlagDisplayed, theDisplay);
735     static Events_Loop* aLoop = Events_Loop::loop();
736     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
737     static const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
738     aECreator->sendUpdated(myObject, EVENT_DISP);
739   }
740 }
741
742 std::shared_ptr<ModelAPI_Data> Model_Data::invalidPtr()
743 {
744   return kInvalid;
745 }
746
747 std::shared_ptr<ModelAPI_Data> Model_Data::invalidData()
748 {
749   return kInvalid;
750 }
751
752 std::shared_ptr<ModelAPI_Object> Model_Data::owner()
753 {
754   return myObject;
755 }
756
757 bool Model_Data::isPrecedingAttribute(const std::string& theAttribute1,
758                                       const std::string& theAttribute2) const
759 {
760   AttributeMap::const_iterator aFound1 = myAttrs.find(theAttribute1);
761   AttributeMap::const_iterator aFound2 = myAttrs.find(theAttribute2);
762   if (aFound2 == myAttrs.end())
763     return true;
764   else if (aFound1 == myAttrs.end())
765     return false;
766   return aFound1->second.second < aFound2->second.second;
767 }