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