Salome HOME
Copyright update 2020
[modules/shaper.git] / src / Model / Model_Data.cpp
1 // Copyright (C) 2014-2020  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include <Model_Data.h>
21 #include <Model_AttributeDocRef.h>
22 #include <Model_AttributeInteger.h>
23 #include <Model_AttributeDouble.h>
24 #include <Model_AttributeDoubleArray.h>
25 #include <Model_AttributeReference.h>
26 #include <Model_AttributeRefAttr.h>
27 #include <Model_AttributeRefList.h>
28 #include <Model_AttributeRefAttrList.h>
29 #include <Model_AttributeBoolean.h>
30 #include <Model_AttributeString.h>
31 #include <Model_AttributeStringArray.h>
32 #include <Model_AttributeSelection.h>
33 #include <Model_AttributeSelectionList.h>
34 #include <Model_AttributeIntArray.h>
35 #include <Model_AttributeTables.h>
36 #include <Model_Events.h>
37 #include <Model_Expression.h>
38 #include <Model_Tools.h>
39 #include <Model_Validator.h>
40
41 #include <ModelAPI_Feature.h>
42 #include <ModelAPI_Result.h>
43 #include <ModelAPI_ResultParameter.h>
44 #include <ModelAPI_ResultConstruction.h>
45 #include <ModelAPI_Validator.h>
46 #include <ModelAPI_Session.h>
47 #include <ModelAPI_ResultPart.h>
48 #include <ModelAPI_Tools.h>
49
50 #include <GeomDataAPI_Point.h>
51 #include <GeomDataAPI_Point2D.h>
52 #include <GeomDataAPI_Point2DArray.h>
53
54 #include <GeomData_Point.h>
55 #include <GeomData_Point2D.h>
56 #include <GeomData_Point2DArray.h>
57 #include <GeomData_Dir.h>
58 #include <Events_Loop.h>
59 #include <Events_InfoMessage.h>
60
61 #include <TDataStd_Name.hxx>
62 #include <TDataStd_AsciiString.hxx>
63 #include <TDataStd_UAttribute.hxx>
64 #include <TDF_ChildIDIterator.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 static const 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 static const Standard_GUID kGroupAttributeGroupID("df64ea4c-fc42-4bf8-ad7e-08f7a54bf1b8");
86 static const Standard_GUID kGroupAttributeID("ebdcb22a-e045-455b-9a7f-cfd38d68e185");
87
88 // id of attribute to store the version of the feature
89 static const Standard_GUID kVERSION_ID("61cdb78a-1ba7-4942-976f-63bea7f4a2b1");
90
91
92 Model_Data::Model_Data() : mySendAttributeUpdated(true), myWasChangedButBlocked(false)
93 {
94 }
95
96 void Model_Data::setLabel(TDF_Label theLab)
97 {
98   myLab = theLab;
99   // set or get the default flags
100   if (!myLab.FindAttribute(TDataStd_BooleanArray::GetID(), myFlags)) {
101     // set default values if not found
102     myFlags = TDataStd_BooleanArray::Set(myLab, 0, 2);
103     myFlags->SetValue(kFlagInHistory, Standard_True); // is in history by default is true
104     myFlags->SetValue(kFlagDisplayed, Standard_True); // is displayed by default is true
105     myFlags->SetValue(kFlagDeleted, Standard_False); // is deleted by default is false
106   }
107 }
108
109 std::string Model_Data::name()
110 {
111   Handle(TDataStd_Name) aName;
112   if (shapeLab().FindAttribute(TDataStd_Name::GetID(), aName)) {
113 #ifdef DEBUG_NAMES
114     myObject->myName = TCollection_AsciiString(aName->Get()).ToCString();
115 #endif
116     return std::string(TCollection_AsciiString(aName->Get()).ToCString());
117   }
118   return "";  // not defined
119 }
120
121 void Model_Data::setName(const std::string& theName)
122 {
123   bool isModified = false;
124   std::string anOldName = name();
125   Handle(TDataStd_Name) aName;
126   if (!shapeLab().FindAttribute(TDataStd_Name::GetID(), aName)) {
127     TDataStd_Name::Set(shapeLab(), theName.c_str());
128     isModified = true;
129   } else {
130     isModified = !aName->Get().IsEqual(theName.c_str());
131     if (isModified) {
132       aName->Set(theName.c_str());
133
134       // check the name of result is defined by user
135       // (name of result does not composed of the name of feature and the result index)
136       bool isUserDefined = true;
137       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myObject);
138       if (aResult) {
139         std::string aDefaultName = ModelAPI_Tools::getDefaultName(aResult, false).first;
140         isUserDefined = aDefaultName != theName;
141       }
142       if (isUserDefined) {
143         // name is user-defined, thus special attribute is set
144         TDataStd_UAttribute::Set(shapeLab(), kUSER_DEFINED_NAME);
145       }
146     }
147   }
148   if (mySendAttributeUpdated && isModified)
149     ModelAPI_ObjectRenamedMessage::send(myObject, anOldName, theName, this);
150   if (isModified && myObject && myObject->document()) {
151     std::dynamic_pointer_cast<Model_Document>(myObject->document())->
152       changeNamingName(anOldName, theName, shapeLab());
153   }
154 #ifdef DEBUG_NAMES
155   myObject->myName = theName;
156 #endif
157 }
158
159 bool Model_Data::hasUserDefinedName() const
160 {
161   return shapeLab().IsAttribute(kUSER_DEFINED_NAME);
162 }
163
164 std::string Model_Data::version()
165 {
166   Handle(TDataStd_Name) aVersionAttr;
167   std::string aVersion;
168   if (shapeLab().FindAttribute(kVERSION_ID, aVersionAttr))
169     aVersion = TCollection_AsciiString(aVersionAttr->Get()).ToCString();
170   return aVersion;
171 }
172
173 void Model_Data::setVersion(const std::string& theVersion)
174 {
175   Handle(TDataStd_Name) aVersionAttr;
176   std::string aVersion;
177   if (!shapeLab().FindAttribute(kVERSION_ID, aVersionAttr))
178     aVersionAttr = TDataStd_Name::Set(shapeLab(), kVERSION_ID, TCollection_ExtendedString());
179   aVersionAttr->Set(theVersion.c_str());
180 }
181
182 AttributePtr Model_Data::addAttribute(
183   const std::string& theID, const std::string theAttrType, const int theIndex)
184 {
185   AttributePtr aResult;
186   int anAttrIndex = theIndex == -1 ? int(myAttrs.size()) + 1 : theIndex;
187   TDF_Label anAttrLab = myLab.FindChild(anAttrIndex);
188   ModelAPI_Attribute* anAttr = 0;
189   if (theAttrType == ModelAPI_AttributeDocRef::typeId()) {
190     anAttr = new Model_AttributeDocRef(anAttrLab);
191   } else if (theAttrType == Model_AttributeInteger::typeId()) {
192     anAttr = new Model_AttributeInteger(anAttrLab);
193   } else if (theAttrType == ModelAPI_AttributeDouble::typeId()) {
194     anAttr = new Model_AttributeDouble(anAttrLab);
195   } else if (theAttrType == Model_AttributeBoolean::typeId()) {
196     anAttr = new Model_AttributeBoolean(anAttrLab);
197   } else if (theAttrType == Model_AttributeString::typeId()) {
198     anAttr = new Model_AttributeString(anAttrLab);
199   } else if (theAttrType == Model_AttributeStringArray::typeId()) {
200     anAttr = new Model_AttributeStringArray(anAttrLab);
201   } else if (theAttrType == ModelAPI_AttributeReference::typeId()) {
202     anAttr = new Model_AttributeReference(anAttrLab);
203   } else if (theAttrType == ModelAPI_AttributeSelection::typeId()) {
204     anAttr = new Model_AttributeSelection(anAttrLab);
205   } else if (theAttrType == ModelAPI_AttributeSelectionList::typeId()) {
206     anAttr = new Model_AttributeSelectionList(anAttrLab);
207   } else if (theAttrType == ModelAPI_AttributeRefAttr::typeId()) {
208     anAttr = new Model_AttributeRefAttr(anAttrLab);
209   } else if (theAttrType == ModelAPI_AttributeRefList::typeId()) {
210     anAttr = new Model_AttributeRefList(anAttrLab);
211   } else if (theAttrType == ModelAPI_AttributeRefAttrList::typeId()) {
212     anAttr = new Model_AttributeRefAttrList(anAttrLab);
213   } else if (theAttrType == ModelAPI_AttributeIntArray::typeId()) {
214     anAttr = new Model_AttributeIntArray(anAttrLab);
215   } else if (theAttrType == ModelAPI_AttributeDoubleArray::typeId()) {
216     anAttr = new Model_AttributeDoubleArray(anAttrLab);
217   } else if (theAttrType == ModelAPI_AttributeTables::typeId()) {
218     anAttr = new Model_AttributeTables(anAttrLab);
219   }
220   // create also GeomData attributes here because only here the OCAF structure is known
221   else if (theAttrType == GeomData_Point::typeId()) {
222     GeomData_Point* anAttribute = new GeomData_Point();
223     bool anAllInitialized = true;
224     for (int aComponent = 0; aComponent < GeomData_Point::NUM_COMPONENTS; ++aComponent) {
225       TDF_Label anExpressionLab = anAttrLab.FindChild(aComponent + 1);
226       anAttribute->myExpression[aComponent].reset(new Model_ExpressionDouble(anExpressionLab));
227       anAllInitialized = anAllInitialized && anAttribute->myExpression[aComponent]->isInitialized();
228     }
229     anAttribute->myIsInitialized = anAllInitialized;
230     anAttr = anAttribute;
231   } else if (theAttrType == GeomData_Dir::typeId()) {
232     anAttr = new GeomData_Dir(anAttrLab);
233   } else if (theAttrType == GeomData_Point2D::typeId()) {
234     GeomData_Point2D* anAttribute = new GeomData_Point2D();
235     bool anAllInitialized = true;
236     for (int aComponent = 0; aComponent < GeomData_Point2D::NUM_COMPONENTS; ++aComponent) {
237       TDF_Label anExpressionLab = anAttrLab.FindChild(aComponent + 1);
238       anAttribute->myExpression[aComponent].reset(new Model_ExpressionDouble(anExpressionLab));
239       anAllInitialized = anAllInitialized && anAttribute->myExpression[aComponent]->isInitialized();
240     }
241     anAttribute->myIsInitialized = anAllInitialized;
242     anAttr = anAttribute;
243   } else if (theAttrType == GeomData_Point2DArray::typeId()) {
244     anAttr = new GeomData_Point2DArray(anAttrLab);
245   }
246
247   if (anAttr) {
248     aResult = std::shared_ptr<ModelAPI_Attribute>(anAttr);
249     myAttrs[theID] = std::pair<AttributePtr, int>(aResult, anAttrIndex);
250     anAttr->setObject(myObject);
251     anAttr->setID(theID);
252   } else {
253     Events_InfoMessage("Model_Data",
254       "Can not create unknown type of attribute %1").arg(theAttrType).send();
255   }
256   return aResult;
257 }
258
259 AttributePtr Model_Data::addFloatingAttribute(
260   const std::string& theID, const std::string theAttrType, const std::string& theGroup)
261 {
262   // compute the index of the attribute placement
263   int anIndex;
264   TDF_Label aLab;
265   if (myLab.IsAttribute(TDF_TagSource::GetID())) {
266     // check this is re-init of attributes, so, check attribute with this name already there
267     TDF_ChildIDIterator anIter(myLab, kGroupAttributeID, false);
268     for(; anIter.More(); anIter.Next()) {
269       TCollection_AsciiString aThisName(Handle(TDataStd_Name)::DownCast(anIter.Value())->Get());
270       if (theID == aThisName.ToCString()) {
271         TDF_Label aLab = anIter.Value()->Label();
272         Handle(TDataStd_Name) aGName;
273         if (aLab.FindAttribute(kGroupAttributeGroupID, aGName)) {
274           TCollection_AsciiString aGroupName(aGName->Get());
275           if (theGroup == aGroupName.ToCString()) {
276             return addAttribute(theGroup + "__" + theID, theAttrType, aLab.Tag());
277           }
278         }
279       }
280     }
281     aLab = myLab.NewChild(); // already exists a floating attribute, create the next
282     anIndex = aLab.Tag();
283   } else { // put the first floating attribute, quite far from other standard attributes
284     anIndex = int(myAttrs.size()) + 1000;
285     TDF_TagSource::Set(myLab)->Set(anIndex);
286     aLab = myLab.FindChild(anIndex, true);
287   }
288   // store the group ID and the attribute ID (to restore correctly)
289   TDataStd_Name::Set(aLab, kGroupAttributeGroupID, theGroup.c_str());
290   TDataStd_Name::Set(aLab, kGroupAttributeID, theID.c_str());
291
292   return addAttribute(theGroup + "__" + theID, theAttrType, anIndex);
293 }
294
295 void Model_Data::allGroups(std::list<std::string>& theGroups)
296 {
297   std::set<std::string> alreadyThere;
298   for(TDF_ChildIDIterator aGroup(myLab, kGroupAttributeGroupID); aGroup.More(); aGroup.Next()) {
299     Handle(TDataStd_Name) aGroupAttr = Handle(TDataStd_Name)::DownCast(aGroup.Value());
300     std::string aGroupID = TCollection_AsciiString(aGroupAttr->Get()).ToCString();
301     if (alreadyThere.find(aGroupID) == alreadyThere.end()) {
302       theGroups.push_back(aGroupID);
303       alreadyThere.insert(aGroupID);
304     }
305   }
306 }
307
308 void Model_Data::attributesOfGroup(const std::string& theGroup,
309   std::list<std::shared_ptr<ModelAPI_Attribute> >& theAttrs)
310 {
311   for(TDF_ChildIDIterator aGroup(myLab, kGroupAttributeGroupID); aGroup.More(); aGroup.Next()) {
312     Handle(TDataStd_Name) aGroupID = Handle(TDataStd_Name)::DownCast(aGroup.Value());
313     if (aGroupID->Get().IsEqual(theGroup.c_str())) {
314       Handle(TDataStd_Name) anID;
315       if (aGroup.Value()->Label().FindAttribute(kGroupAttributeID, anID)) {
316         TCollection_AsciiString anAsciiID(aGroupID->Get() + "__" + anID->Get());
317         theAttrs.push_back(attribute(anAsciiID.ToCString()));
318       }
319     }
320   }
321 }
322
323 void Model_Data::removeAttributes(const std::string& theGroup)
324 {
325   TDF_LabelList aLabsToRemove; // collect labels that must be erased after the cycle
326   for(TDF_ChildIDIterator aGroup(myLab, kGroupAttributeGroupID); aGroup.More(); aGroup.Next()) {
327     Handle(TDataStd_Name) aGroupID = Handle(TDataStd_Name)::DownCast(aGroup.Value());
328     if (aGroupID->Get().IsEqual(theGroup.c_str())) {
329       Handle(TDataStd_Name) anID;
330       if (!aGroup.Value()->Label().IsNull() &&
331           aGroup.Value()->Label().FindAttribute(kGroupAttributeID, anID)) {
332         aLabsToRemove.Append(aGroup.Value()->Label());
333       }
334       TCollection_AsciiString anAsciiID(aGroupID->Get() + "__" + anID->Get());
335       myAttrs.erase(anAsciiID.ToCString());
336     }
337   }
338   for(TDF_LabelList::Iterator aLab(aLabsToRemove); aLab.More(); aLab.Next()) {
339     aLab.ChangeValue().ForgetAllAttributes(true);
340   }
341 }
342
343 void Model_Data::clearAttributes()
344 {
345   myAttrs.clear();
346 }
347
348
349
350 // macro for the generic returning of the attribute by the ID
351 #define GET_ATTRIBUTE_BY_ID(ATTR_TYPE, METHOD_NAME) \
352   std::shared_ptr<ATTR_TYPE> Model_Data::METHOD_NAME(const std::string& theID) { \
353     std::shared_ptr<ATTR_TYPE> aRes; \
354     AttributeMap::iterator aFound = myAttrs.find(theID); \
355     if (aFound != myAttrs.end()) { \
356       aRes = std::dynamic_pointer_cast<ATTR_TYPE>(aFound->second.first); \
357     } \
358     return aRes; \
359   }
360 // implement nice getting methods for all ModelAPI attributes
361 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeDocRef, document);
362 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeDouble, real);
363 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeInteger, integer);
364 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeBoolean, boolean);
365 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeString, string);
366 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeStringArray, stringArray);
367 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeReference, reference);
368 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeSelection, selection);
369 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeSelectionList, selectionList);
370 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeRefAttr, refattr);
371 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeRefList, reflist);
372 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeRefAttrList, refattrlist);
373 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeIntArray, intArray);
374 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeDoubleArray, realArray);
375 GET_ATTRIBUTE_BY_ID(ModelAPI_AttributeTables, tables);
376
377 std::shared_ptr<ModelAPI_Attribute> Model_Data::attribute(const std::string& theID)
378 {
379   std::shared_ptr<ModelAPI_Attribute> aResult;
380   if (myAttrs.find(theID) == myAttrs.end())  // no such attribute
381     return aResult;
382   return myAttrs[theID].first;
383 }
384
385 const std::string& Model_Data::id(const std::shared_ptr<ModelAPI_Attribute>& theAttr)
386 {
387   AttributeMap::iterator anAttr = myAttrs.begin();
388   for (; anAttr != myAttrs.end(); anAttr++) {
389     if (anAttr->second.first == theAttr)
390       return anAttr->first;
391   }
392   // not found
393   static std::string anEmpty;
394   return anEmpty;
395 }
396
397 bool Model_Data::isEqual(const std::shared_ptr<ModelAPI_Data>& theData)
398 {
399   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theData);
400   if (aData)
401     return myLab.IsEqual(aData->myLab) == Standard_True ;
402   return false;
403 }
404
405 bool Model_Data::isValid()
406 {
407   return !myLab.IsNull() && myLab.HasAttribute();
408 }
409
410 std::list<std::shared_ptr<ModelAPI_Attribute> > Model_Data::attributes(const std::string& theType)
411 {
412   std::list<std::shared_ptr<ModelAPI_Attribute> > aResult;
413   AttributeMap::iterator anAttrsIter = myAttrs.begin();
414   for (; anAttrsIter != myAttrs.end(); anAttrsIter++) {
415     AttributePtr anAttr = anAttrsIter->second.first;
416     if (theType.empty() || anAttr->attributeType() == theType) {
417       aResult.push_back(anAttr);
418     }
419   }
420   return aResult;
421 }
422
423 std::list<std::string> Model_Data::attributesIDs(const std::string& theType)
424 {
425   std::list<std::string> aResult;
426   AttributeMap::iterator anAttrsIter = myAttrs.begin();
427   for (; anAttrsIter != myAttrs.end(); anAttrsIter++) {
428     AttributePtr anAttr = anAttrsIter->second.first;
429     if (theType.empty() || anAttr->attributeType() == theType) {
430       aResult.push_back(anAttrsIter->first);
431     }
432   }
433   return aResult;
434 }
435
436 void Model_Data::sendAttributeUpdated(ModelAPI_Attribute* theAttr)
437 {
438   theAttr->setInitialized();
439   if (theAttr->isArgument()) {
440     if (mySendAttributeUpdated) {
441       if (myObject) {
442         try {
443             myObject->attributeChanged(theAttr->id());
444         } catch(...) {
445           if (owner().get() && owner()->data().get() && owner()->data()->isValid()) {
446             Events_InfoMessage("Model_Data",
447               "%1 has failed during the update").arg(owner()->data()->name()).send();
448           }
449         }
450         static const Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
451         ModelAPI_EventCreator::get()->sendUpdated(myObject, anEvent);
452       }
453     } else {
454       // to avoid too many duplications do not add the same like the last
455       if (myWasChangedButBlocked.empty() || *(myWasChangedButBlocked.rbegin()) != theAttr)
456         myWasChangedButBlocked.push_back(theAttr);
457     }
458   } else {
459     // trim: need to redisplay or set color in the python script
460     if (myObject && (theAttr->attributeType() == "Point2D" || theAttr->id() == "Color" ||
461       theAttr->id() == "Transparency" || theAttr->id() == "Deflection" ||
462       theAttr->id() == "Iso_lines" || theAttr->id() == "Show_Iso_lines")) {
463       static const Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
464       ModelAPI_EventCreator::get()->sendUpdated(myObject, anEvent);
465     }
466   }
467 }
468
469 bool Model_Data::blockSendAttributeUpdated(const bool theBlock, const bool theSendMessage)
470 {
471   bool aWasBlocked = !mySendAttributeUpdated;
472   if (mySendAttributeUpdated == theBlock) {
473     mySendAttributeUpdated = !theBlock;
474     if (mySendAttributeUpdated && !myWasChangedButBlocked.empty()) {
475       // so, now it is ok to send the update signal
476       if (theSendMessage) {
477         // make a copy to avoid iteration on modified list
478         // (may be cleared by attribute changed call)
479         std::list<ModelAPI_Attribute*> aWasChangedButBlocked = myWasChangedButBlocked;
480         myWasChangedButBlocked.clear();
481         std::list<ModelAPI_Attribute*>::iterator aChangedIter = aWasChangedButBlocked.begin();
482         for(; aChangedIter != aWasChangedButBlocked.end(); aChangedIter++) {
483           try {
484             myObject->attributeChanged((*aChangedIter)->id());
485           } catch(...) {
486             if (owner().get() && owner()->data().get() && owner()->data()->isValid()) {
487               Events_InfoMessage("Model_Data",
488                 "%1 has failed during the update").arg(owner()->data()->name()).send();
489             }
490           }
491         }
492         static const Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
493         ModelAPI_EventCreator::get()->sendUpdated(myObject, anEvent);
494       } else {
495         myWasChangedButBlocked.clear();
496       }
497     }
498   }
499   return aWasBlocked;
500 }
501
502 void Model_Data::erase()
503 {
504   if (!myLab.IsNull()) {
505     if (myLab.HasAttribute()) {
506       // remove in order to clear back references in other objects
507       std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
508       referencesToObjects(aRefs);
509       std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator
510         anAttrIter = aRefs.begin();
511       for(; anAttrIter != aRefs.end(); anAttrIter++) {
512         std::list<ObjectPtr>::iterator aReferenced = anAttrIter->second.begin();
513         for(; aReferenced != anAttrIter->second.end(); aReferenced++) {
514           if (aReferenced->get() && (*aReferenced)->data()->isValid()) {
515             std::shared_ptr<Model_Data> aData =
516               std::dynamic_pointer_cast<Model_Data>((*aReferenced)->data());
517             aData->removeBackReference(myAttrs[anAttrIter->first].first);
518           }
519         }
520       }
521     }
522     myAttrs.clear();
523     myLab.ForgetAllAttributes();
524   }
525 }
526
527 // indexes in the state array
528 enum StatesIndexes {
529   STATE_INDEX_STATE = 1, // the state type itself
530   STATE_INDEX_TRANSACTION = 2, // transaction ID
531 };
532
533 /// Returns the label array, initializes it by default values if not exists
534 static Handle(TDataStd_IntegerArray) stateArray(TDF_Label& theLab)
535 {
536   Handle(TDataStd_IntegerArray) aStateArray;
537   if (!theLab.FindAttribute(TDataStd_IntegerArray::GetID(), aStateArray)) {
538     aStateArray = TDataStd_IntegerArray::Set(theLab, 1, 2);
539     aStateArray->SetValue(STATE_INDEX_STATE, ModelAPI_StateMustBeUpdated); // default state
540     aStateArray->SetValue(STATE_INDEX_TRANSACTION, 0); // default transaction ID (not existing)
541   }
542   return aStateArray;
543 }
544
545 void Model_Data::execState(const ModelAPI_ExecState theState)
546 {
547   if (theState != ModelAPI_StateNothing) {
548     if (stateArray(myLab)->Value(STATE_INDEX_STATE) != (int)theState) {
549       stateArray(myLab)->SetValue(STATE_INDEX_STATE, (int)theState);
550     }
551   }
552 }
553
554 ModelAPI_ExecState Model_Data::execState()
555 {
556   return ModelAPI_ExecState(stateArray(myLab)->Value(STATE_INDEX_STATE));
557 }
558
559 int Model_Data::updateID()
560 {
561   return stateArray(myLab)->Value(STATE_INDEX_TRANSACTION);
562 }
563
564 void Model_Data::setUpdateID(const int theID)
565 {
566   stateArray(myLab)->SetValue(STATE_INDEX_TRANSACTION, theID);
567 }
568
569 void Model_Data::setError(const std::string& theError, bool theSend)
570 {
571   execState(ModelAPI_StateExecFailed);
572   if (theSend) {
573     Events_InfoMessage("Model_Data", theError).send();
574   }
575   TDataStd_AsciiString::Set(myLab, theError.c_str());
576 }
577
578 void Model_Data::eraseErrorString()
579 {
580   myLab.ForgetAttribute(TDataStd_AsciiString::GetID());
581 }
582
583 std::string Model_Data::error() const
584 {
585   Handle(TDataStd_AsciiString) anErrorAttr;
586   if (myLab.FindAttribute(TDataStd_AsciiString::GetID(), anErrorAttr)) {
587     return std::string(anErrorAttr->Get().ToCString());
588   }
589   return std::string();
590 }
591
592 int Model_Data::featureId() const
593 {
594   return myLab.Father().Tag(); // tag of the feature label
595 }
596
597 void Model_Data::removeBackReference(ObjectPtr theObject, std::string theAttrID)
598 {
599   AttributePtr anAttribute = theObject->data()->attribute(theAttrID);
600   removeBackReference(anAttribute);
601 }
602
603 void Model_Data::removeBackReference(AttributePtr theAttr)
604 {
605   if (myRefsToMe.find(theAttr) == myRefsToMe.end())
606     return;
607
608   myRefsToMe.erase(theAttr);
609
610   // remove concealment immediately: on deselection it must be possible to reselect in GUI the same
611   FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(theAttr->owner());
612   if (aFeatureOwner.get() &&
613     ModelAPI_Session::get()->validators()->isConcealed(aFeatureOwner->getKind(), theAttr->id())) {
614     updateConcealmentFlag();
615   }
616 }
617
618 void Model_Data::addBackReference(FeaturePtr theFeature, std::string theAttrID,
619    const bool theApplyConcealment)
620 {
621   addBackReference(ObjectPtr(theFeature), theAttrID);
622
623   if (theApplyConcealment &&  theFeature->isStable() &&
624       ModelAPI_Session::get()->validators()->isConcealed(theFeature->getKind(), theAttrID)) {
625     std::shared_ptr<ModelAPI_Result> aRes = std::dynamic_pointer_cast<ModelAPI_Result>(myObject);
626     // the second condition is for history upper than concealment causer, so the feature result may
627     // be displayed and previewed; also for avoiding of quick show/hide on history
628     // moving deep down
629     if (aRes && !theFeature->isDisabled()) {
630       aRes->setIsConcealed(true, theFeature->getKind() == "RemoveResults");
631     }
632   }
633 }
634
635 void Model_Data::addBackReference(ObjectPtr theObject, std::string theAttrID)
636 {
637   // it is possible to add the same attribute twice: may be last time the owner was not Stable...
638   AttributePtr anAttribute = theObject->data()->attribute(theAttrID);
639   if (myRefsToMe.find(anAttribute) == myRefsToMe.end())
640     myRefsToMe.insert(anAttribute);
641 }
642
643 void Model_Data::updateConcealmentFlag()
644 {
645   std::set<AttributePtr>::iterator aRefsIter = myRefsToMe.begin();
646   for(; aRefsIter != myRefsToMe.end(); aRefsIter++) {
647     if (aRefsIter->get()) {
648       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefsIter)->owner());
649       if (aFeature.get() && !aFeature->isDisabled() && aFeature->isStable()) {
650         if (ModelAPI_Session::get()->validators()->isConcealed(
651               aFeature->getKind(), (*aRefsIter)->id())) {
652           std::shared_ptr<ModelAPI_Result> aRes =
653             std::dynamic_pointer_cast<ModelAPI_Result>(myObject);
654           if (aRes.get()) {
655             if (aRes->groupName() != ModelAPI_ResultConstruction::group()) {
656               aRes->setIsConcealed(true); // set concealed
657               return;
658             } else if (aFeature->getKind() == "RemoveResults") {
659               aRes->setIsConcealed(true, true);
660               return;
661             }
662           }
663         }
664       }
665     }
666   }
667   std::shared_ptr<ModelAPI_Result> aRes =
668     std::dynamic_pointer_cast<ModelAPI_Result>(myObject);
669   if (aRes.get()) {
670     aRes->setIsConcealed(false);
671   }
672 }
673
674 std::set<std::string> set_union(const std::set<std::string>& theLeft,
675                                 const std::set<std::string>& theRight)
676 {
677   std::set<std::string> aResult;
678   aResult.insert(theLeft.begin(), theLeft.end());
679   aResult.insert(theRight.begin(), theRight.end());
680   return aResult;
681 }
682
683 std::set<std::string> usedParameters(const AttributePointPtr& theAttribute)
684 {
685   std::set<std::string> anUsedParameters;
686   for (int aComponent = 0; aComponent < 3; ++aComponent)
687     anUsedParameters = set_union(anUsedParameters, theAttribute->usedParameters(aComponent));
688   return anUsedParameters;
689 }
690
691 std::set<std::string> usedParameters(const AttributePoint2DPtr& theAttribute)
692 {
693   std::set<std::string> anUsedParameters;
694   for (int aComponent = 0; aComponent < 2; ++aComponent)
695     anUsedParameters = set_union(anUsedParameters, theAttribute->usedParameters(aComponent));
696   return anUsedParameters;
697 }
698
699 std::list<ResultParameterPtr> findVariables(const std::set<std::string>& theParameters,
700                                             const DocumentPtr& theDocument)
701 {
702   std::list<ResultParameterPtr> aResult;
703   std::set<std::string>::const_iterator aParamIt = theParameters.cbegin();
704   for (; aParamIt != theParameters.cend(); ++aParamIt) {
705     const std::string& aName = *aParamIt;
706     double aValue;
707     ResultParameterPtr aParam;
708     // theSearcher is not needed here: in expressions
709     // of features the parameters history is not needed
710     if (ModelAPI_Tools::findVariable(FeaturePtr(), aName, aValue, aParam, theDocument))
711       aResult.push_back(aParam);
712   }
713   return aResult;
714 }
715
716 void Model_Data::referencesToObjects(
717   std::list<std::pair<std::string, std::list<ObjectPtr> > >& theRefs)
718 {
719   static Model_ValidatorsFactory* aValidators =
720     static_cast<Model_ValidatorsFactory*>(ModelAPI_Session::get()->validators());
721   FeaturePtr aMyFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(myObject);
722
723   AttributeMap::iterator anAttrIt = myAttrs.begin();
724   std::list<ObjectPtr> aReferenced; // not inside of cycle to avoid excess memory management
725   for(; anAttrIt != myAttrs.end(); anAttrIt++) {
726     AttributePtr anAttr = anAttrIt->second.first;
727     // skip not-case attributes, that really may refer to anything not-used (issue 671)
728     if (aMyFeature.get() && !aValidators->isCase(aMyFeature, anAttr->id()))
729       continue;
730
731     std::string aType = anAttr->attributeType();
732     if (aType == ModelAPI_AttributeReference::typeId()) { // reference to object
733       std::shared_ptr<ModelAPI_AttributeReference> aRef = std::dynamic_pointer_cast<
734           ModelAPI_AttributeReference>(anAttr);
735       aReferenced.push_back(aRef->value());
736     } else if (aType == ModelAPI_AttributeRefAttr::typeId()) { // reference to attribute or object
737       std::shared_ptr<ModelAPI_AttributeRefAttr> aRef = std::dynamic_pointer_cast<
738           ModelAPI_AttributeRefAttr>(anAttr);
739       if (aRef->isObject()) {
740         aReferenced.push_back(aRef->object());
741       } else {
742         AttributePtr anAttr = aRef->attr();
743         if (anAttr.get())
744           aReferenced.push_back(anAttr->owner());
745       }
746     } else if (aType == ModelAPI_AttributeRefList::typeId()) { // list of references
747       aReferenced = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(anAttr)->list();
748     }
749     else if (aType == ModelAPI_AttributeSelection::typeId()) { // selection attribute
750       std::shared_ptr<ModelAPI_AttributeSelection> aRef = std::dynamic_pointer_cast<
751         ModelAPI_AttributeSelection>(anAttr);
752       FeaturePtr aRefFeat = aRef->contextFeature();
753       if (aRefFeat.get()) { // reference to all results of the referenced feature
754         const std::list<ResultPtr>& allRes = aRefFeat->results();
755         std::list<ResultPtr>::const_iterator aRefRes = allRes.cbegin();
756         for(; aRefRes != allRes.cend(); aRefRes++) {
757           aReferenced.push_back(*aRefRes);
758         }
759       } else {
760         aReferenced.push_back(aRef->context());
761       }
762     } else if (aType == ModelAPI_AttributeSelectionList::typeId()) { // list of selection attributes
763       std::shared_ptr<ModelAPI_AttributeSelectionList> aRef = std::dynamic_pointer_cast<
764           ModelAPI_AttributeSelectionList>(anAttr);
765       for(int a = 0, aSize = aRef->size(); a < aSize; ++a) {
766         FeaturePtr aRefFeat = aRef->value(a)->contextFeature();
767         if (aRefFeat.get()) { // reference to all results of the referenced feature
768           const std::list<ResultPtr>& allRes = aRefFeat->results();
769           std::list<ResultPtr>::const_iterator aRefRes = allRes.cbegin();
770           for (; aRefRes != allRes.cend(); aRefRes++) {
771             aReferenced.push_back(*aRefRes);
772           }
773         } else {
774           aReferenced.push_back(aRef->value(a)->context());
775         }
776       }
777     } else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
778       std::shared_ptr<ModelAPI_AttributeRefAttrList> aRefAttr = std::dynamic_pointer_cast<
779           ModelAPI_AttributeRefAttrList>(anAttr);
780       std::list<std::pair<ObjectPtr, AttributePtr> > aRefs = aRefAttr->list();
781       std::list<std::pair<ObjectPtr, AttributePtr> >::const_iterator anIt = aRefs.begin(),
782                                                                      aLast = aRefs.end();
783       for (; anIt != aLast; anIt++) {
784         aReferenced.push_back(anIt->first);
785       }
786     } else if (aType == ModelAPI_AttributeInteger::typeId()) { // integer attribute
787       AttributeIntegerPtr anAttribute =
788           std::dynamic_pointer_cast<ModelAPI_AttributeInteger>(anAttr);
789       std::set<std::string> anUsedParameters = anAttribute->usedParameters();
790       std::list<ResultParameterPtr> aParameters =
791         findVariables(anUsedParameters, owner()->document());
792       aReferenced.insert(aReferenced.end(), aParameters.begin(), aParameters.end());
793     } else if (aType == ModelAPI_AttributeDouble::typeId()) { // double attribute
794       AttributeDoublePtr anAttribute =
795           std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(anAttr);
796       std::set<std::string> anUsedParameters = anAttribute->usedParameters();
797       std::list<ResultParameterPtr> aParameters =
798         findVariables(anUsedParameters, owner()->document());
799       aReferenced.insert(aReferenced.end(), aParameters.begin(), aParameters.end());
800     } else if (aType == GeomDataAPI_Point::typeId()) { // point attribute
801       AttributePointPtr anAttribute =
802         std::dynamic_pointer_cast<GeomDataAPI_Point>(anAttr);
803       std::set<std::string> anUsedParameters = usedParameters(anAttribute);
804       std::list<ResultParameterPtr> aParameters =
805         findVariables(anUsedParameters, owner()->document());
806       aReferenced.insert(aReferenced.end(), aParameters.begin(), aParameters.end());
807     } else if (aType == GeomDataAPI_Point2D::typeId()) { // point attribute
808       AttributePoint2DPtr anAttribute =
809         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttr);
810       std::set<std::string> anUsedParameters = usedParameters(anAttribute);
811       std::list<ResultParameterPtr> aParameters =
812         findVariables(anUsedParameters, owner()->document());
813       aReferenced.insert(aReferenced.end(), aParameters.begin(), aParameters.end());
814     } else
815       continue; // nothing to do, not reference
816
817     if (!aReferenced.empty()) {
818       theRefs.push_back(
819           std::pair<std::string, std::list<ObjectPtr> >(anAttrIt->first, aReferenced));
820       aReferenced.clear();
821     }
822   }
823 }
824
825 void Model_Data::copyTo(std::shared_ptr<ModelAPI_Data> theTarget)
826 {
827   TDF_Label aTargetRoot = std::dynamic_pointer_cast<Model_Data>(theTarget)->label();
828   Model_Tools::copyAttrs(myLab, aTargetRoot);
829   // reinitialize Model_Attributes by TDF_Attributes set
830   std::shared_ptr<Model_Data> aTData = std::dynamic_pointer_cast<Model_Data>(theTarget);
831   aTData->myAttrs.clear();
832   theTarget->owner()->initAttributes(); // reinitialize feature attributes
833 }
834
835 bool Model_Data::isInHistory()
836 {
837   return myFlags->Value(kFlagInHistory) == Standard_True;
838 }
839
840 void Model_Data::setIsInHistory(const bool theFlag)
841 {
842   return myFlags->SetValue(kFlagInHistory, theFlag);
843 }
844
845 bool Model_Data::isDeleted()
846 {
847   return myFlags->Value(kFlagDeleted) == Standard_True;
848 }
849
850 void Model_Data::setIsDeleted(const bool theFlag)
851 {
852   return myFlags->SetValue(kFlagDeleted, theFlag);
853 }
854
855 bool Model_Data::isDisplayed()
856 {
857   if (!myObject.get() || !myObject->document().get() || // object is in valid
858       myFlags->Value(kFlagDisplayed) != Standard_True) // or it was not displayed before
859     return false;
860   if (myObject->document()->isActive()) // for active documents it must be ok anyway
861     return true;
862   // any object from the root document except part result may be displayed
863   if (myObject->document() == ModelAPI_Session::get()->moduleDocument() &&
864       myObject->groupName() != ModelAPI_ResultPart::group())
865     return true;
866   return false;
867 }
868
869 void Model_Data::setDisplayed(const bool theDisplay)
870 {
871   if (theDisplay != isDisplayed()) {
872     myFlags->SetValue(kFlagDisplayed, theDisplay);
873     static Events_Loop* aLoop = Events_Loop::loop();
874     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
875     static const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
876     aECreator->sendUpdated(myObject, EVENT_DISP);
877   }
878 }
879
880 std::shared_ptr<ModelAPI_Data> Model_Data::invalidPtr()
881 {
882   return kInvalid;
883 }
884
885 std::shared_ptr<ModelAPI_Data> Model_Data::invalidData()
886 {
887   return kInvalid;
888 }
889
890 std::shared_ptr<ModelAPI_Object> Model_Data::owner()
891 {
892   return myObject;
893 }
894
895 bool Model_Data::isPrecedingAttribute(const std::string& theAttribute1,
896                                       const std::string& theAttribute2) const
897 {
898   AttributeMap::const_iterator aFound1 = myAttrs.find(theAttribute1);
899   AttributeMap::const_iterator aFound2 = myAttrs.find(theAttribute2);
900   if (aFound2 == myAttrs.end())
901     return true;
902   else if (aFound1 == myAttrs.end())
903     return false;
904   return aFound1->second.second < aFound2->second.second;
905 }