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