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