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