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