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