Salome HOME
Issue #903 - Parameter is not created, if expression contains not created parameter
[modules/shaper.git] / src / ParametersPlugin / ParametersPlugin_EvalListener.cpp
1 /*
2  * ParametersPlugin_EvalListener.cpp
3  *
4  *  Created on: Apr 28, 2015
5  *      Author: sbh
6  */
7
8 #include <pyconfig.h>
9
10 #include <ParametersPlugin_EvalListener.h>
11 #include <ParametersPlugin_Parameter.h>
12 #include <ParametersPlugin_PyInterp.h>
13
14 #include <Events_Error.h>
15
16 #include <ModelAPI_AttributeRefList.h>
17 #include <ModelAPI_AttributeString.h>
18 #include <ModelAPI_AttributeValidator.h>
19 #include <ModelAPI_Document.h>
20 #include <ModelAPI_Events.h>
21 #include <ModelAPI_Session.h>
22 #include <ModelAPI_Tools.h>
23
24 #include <ModelAPI_AttributeDouble.h>
25 #include <GeomDataAPI_Point.h>
26 #include <GeomDataAPI_Point2D.h>
27
28 #include <string>
29 #include <set>
30 #include <sstream>
31
32 ParametersPlugin_EvalListener::ParametersPlugin_EvalListener()
33 {
34   Events_Loop* aLoop = Events_Loop::loop();
35   const Events_ID kEvaluationEvent = ModelAPI_AttributeEvalMessage::eventId();
36   aLoop->registerListener(this, kEvaluationEvent, NULL, true);
37   const Events_ID kObjectRenamedEvent = ModelAPI_ObjectRenamedMessage::eventId();
38   aLoop->registerListener(this, kObjectRenamedEvent, NULL, true);
39
40   myInterp = std::shared_ptr<ParametersPlugin_PyInterp>(new ParametersPlugin_PyInterp());
41   myInterp->initialize();
42 }
43
44 ParametersPlugin_EvalListener::~ParametersPlugin_EvalListener()
45 {
46 }
47
48 void ParametersPlugin_EvalListener::processEvent(
49     const std::shared_ptr<Events_Message>& theMessage)
50 {
51   if (!theMessage.get())
52     return;
53
54   const Events_ID kEvaluationEvent = ModelAPI_AttributeEvalMessage::eventId();
55   const Events_ID kObjectRenamedEvent = ModelAPI_ObjectRenamedMessage::eventId();
56   if (theMessage->eventID() == kEvaluationEvent) {
57     processEvaluationEvent(theMessage);
58   } else if (theMessage->eventID() == kObjectRenamedEvent) {
59     processObjectRenamedEvent(theMessage);
60   } else {
61     Events_Error::send(std::string("ParametersPlugin python interpreter, unhandled message caught: ")
62                        + theMessage->eventID().eventText());
63   }
64 }
65
66 double ParametersPlugin_EvalListener::evaluate(const std::string& theExpression, std::string& theError, 
67                                                const std::shared_ptr<ModelAPI_Document>& theDocument)
68 {
69   std::list<std::string> anExprParams = myInterp->compile(theExpression);
70   // find expression's params in the model
71   std::list<std::string> aContext;
72   std::list<std::string>::iterator it = anExprParams.begin();
73   for ( ; it != anExprParams.end(); it++) {
74     double aValue;
75     ResultParameterPtr aParamRes;
76     // If variable does not exist python interpreter will generate an error. It is OK.
77     if (!ModelAPI_Tools::findVariable(*it, aValue, aParamRes, theDocument)) continue;
78
79     std::ostringstream sstream;
80     sstream << aValue;
81     std::string aParamValue = sstream.str();
82     aContext.push_back(*it + "=" + aParamValue);
83   }
84   myInterp->extendLocalContext(aContext);
85   double result = myInterp->evaluate(theExpression, theError);
86   myInterp->clearLocalContext();
87   return result;
88 }
89
90 std::set<std::string> toSet(const std::list<std::string>& theContainer)
91 {
92   return std::set<std::string>(theContainer.begin(), theContainer.end());
93 }
94
95 void ParametersPlugin_EvalListener::processEvaluationEvent(
96     const std::shared_ptr<Events_Message>& theMessage)
97 {
98   std::shared_ptr<ModelAPI_AttributeEvalMessage> aMessage =
99       std::dynamic_pointer_cast<ModelAPI_AttributeEvalMessage>(theMessage);
100
101   if (aMessage->attribute()->attributeType() == ModelAPI_AttributeDouble::typeId()) {
102     AttributeDoublePtr anAttribute =
103         std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(aMessage->attribute());
104     std::string anError;
105     double aValue = evaluate(anAttribute->text(), anError, anAttribute->owner()->document());
106     bool isValid = anError.empty();
107     if (isValid)
108       anAttribute->setCalculatedValue(aValue);
109     anAttribute->setUsedParameters(isValid ? toSet(myInterp->compile(anAttribute->text())) : std::set<std::string>());
110     anAttribute->setExpressionInvalid(!isValid);
111     anAttribute->setExpressionError(anAttribute->text().empty() ? "" : anError);
112   } else
113   if (aMessage->attribute()->attributeType() == GeomDataAPI_Point::typeId()) {
114     AttributePointPtr anAttribute =
115         std::dynamic_pointer_cast<GeomDataAPI_Point>(aMessage->attribute());
116     std::string aText[] = {
117       anAttribute->textX(),
118       anAttribute->textY(),
119       anAttribute->textZ()
120     };
121     double aCalculatedValue[] = {
122       anAttribute->x(),
123       anAttribute->y(),
124       anAttribute->z()
125     };
126     for (int i = 0; i < 3; ++i) {
127       std::string anError;
128       double aValue = evaluate(aText[i], anError, anAttribute->owner()->document());
129       bool isValid = anError.empty();
130       if (isValid) aCalculatedValue[i] = aValue;
131       anAttribute->setUsedParameters(i, isValid ? toSet(myInterp->compile(aText[i])) : std::set<std::string>());
132       anAttribute->setExpressionInvalid(i, !isValid);
133       anAttribute->setExpressionError(i, aText[i].empty() ? "" : anError);
134     }
135     anAttribute->setCalculatedValue(aCalculatedValue[0],
136                                     aCalculatedValue[1],
137                                     aCalculatedValue[2]);
138   } else
139   if (aMessage->attribute()->attributeType() == GeomDataAPI_Point2D::typeId()) {
140     AttributePoint2DPtr anAttribute =
141         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aMessage->attribute());
142     std::string aText[] = {
143       anAttribute->textX(),
144       anAttribute->textY()
145     };
146     double aCalculatedValue[] = {
147       anAttribute->x(),
148       anAttribute->y()
149     };
150     for (int i = 0; i < 2; ++i) {
151       std::string anError;
152       double aValue = evaluate(aText[i], anError, anAttribute->owner()->document());
153       bool isValid = anError.empty();
154       if (isValid) aCalculatedValue[i] = aValue;
155       anAttribute->setUsedParameters(i, isValid ? toSet(myInterp->compile(aText[i])) : std::set<std::string>());
156       anAttribute->setExpressionInvalid(i, !isValid);
157       anAttribute->setExpressionError(i, aText[i].empty() ? "" : anError);
158     }
159     anAttribute->setCalculatedValue(aCalculatedValue[0],
160                                     aCalculatedValue[1]);
161   }
162 }
163
164 std::string ParametersPlugin_EvalListener::renameInPythonExpression(
165     const std::string& theExpression,
166     const std::string& theOldName,
167     const std::string& theNewName)
168 {
169   std::string anExpressionString = theExpression;
170
171   std::list<std::pair<int, int> > aPositions =
172       myInterp->positions(anExpressionString, theOldName);
173
174   if (aPositions.empty())
175     return anExpressionString;
176
177   std::map<int, std::list<int> > aLines;
178   std::list<std::pair<int, int> >::const_iterator it = aPositions.begin();
179   for (; it != aPositions.end(); ++it)
180     aLines[it->first].push_back(it->second);
181
182   // Start renaming from the end to keep indexes if theNewName is longer then theOldName
183   std::map<int, std::list<int> >::const_reverse_iterator ritLine = aLines.rbegin();
184   for (; ritLine != aLines.rend(); ++ritLine) {
185     // Calculate the start of the line (find the aLineNo occurrence of "\n" )
186     int aLineNo = ritLine->first - 1;
187     size_t aLineStart = 0;
188     for (int i = 0; i < aLineNo; ++i)
189       aLineStart = anExpressionString.find("\n", aLineStart) + 1;
190
191     const std::list<int>& aColOffsets = ritLine->second;
192     std::list<int>::const_reverse_iterator ritOffset = aColOffsets.rbegin();
193     for (; ritOffset != aColOffsets.rend(); ++ritOffset) {
194       int anOffset = *ritOffset;
195       anExpressionString.replace(aLineStart + anOffset, theOldName.size(), theNewName);
196     }
197   }
198
199   return anExpressionString;
200 }
201
202 void ParametersPlugin_EvalListener::renameInParameter(
203     std::shared_ptr<ParametersPlugin_Parameter> theParameter,
204     const std::string& theOldName,
205     const std::string& theNewName)
206 {
207   std::shared_ptr<ModelAPI_AttributeString> anExpressionAttribute =
208       theParameter->string(ParametersPlugin_Parameter::EXPRESSION_ID());
209
210   std::string anExpressionString = anExpressionAttribute->value();
211   anExpressionString = renameInPythonExpression(anExpressionString,
212                                                 theOldName,
213                                                 theNewName);
214   // Issue #588. No need for reevaluating expression. 
215   // Moreover, current history may not contain necessary parameters.
216   anExpressionAttribute->owner()->data()->blockSendAttributeUpdated(true);
217   anExpressionAttribute->setValue(anExpressionString);
218   anExpressionAttribute->owner()->data()->blockSendAttributeUpdated(false);
219 }
220
221 void ParametersPlugin_EvalListener::renameInAttribute(
222     std::shared_ptr<ModelAPI_Attribute> theAttribute,
223     const std::string& theOldName,
224     const std::string& theNewName)
225 {
226   if (theAttribute->attributeType() == ModelAPI_AttributeDouble::typeId()) {
227     AttributeDoublePtr anAttribute =
228         std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theAttribute);
229     std::string anExpressionString = anAttribute->text();
230     anExpressionString = renameInPythonExpression(anExpressionString,
231                                                   theOldName, theNewName);
232     anAttribute->setText(anExpressionString);
233   } else
234   if (theAttribute->attributeType() == GeomDataAPI_Point::typeId()) {
235     AttributePointPtr anAttribute =
236         std::dynamic_pointer_cast<GeomDataAPI_Point>(theAttribute);
237     std::string anExpressionString[3] = {
238       anAttribute->textX(),
239       anAttribute->textY(),
240       anAttribute->textZ()
241     };
242     for (int i = 0; i < 3; ++i)
243       anExpressionString[i] = renameInPythonExpression(anExpressionString[i],
244                                                        theOldName, theNewName);
245     anAttribute->setText(anExpressionString[0],
246                          anExpressionString[1],
247                          anExpressionString[2]);
248   } else
249   if (theAttribute->attributeType() == GeomDataAPI_Point2D::typeId()) {
250     AttributePoint2DPtr anAttribute =
251         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute);
252     std::string anExpressionString[2] = {
253       anAttribute->textX(),
254       anAttribute->textY()
255     };
256     for (int i = 0; i < 2; ++i)
257       anExpressionString[i] = renameInPythonExpression(anExpressionString[i],
258                                                        theOldName, theNewName);
259     anAttribute->setText(anExpressionString[0],
260                          anExpressionString[1]);
261   }
262 }
263
264 bool isValidAttribute(const AttributePtr& theAttribute)
265 {
266   std::string aValidator, anError;
267   return ModelAPI_Session::get()->validators()->validate(theAttribute, aValidator, anError);
268 }
269
270 void setParameterName(ResultParameterPtr theResultParameter, const std::string& theName)
271 {
272   theResultParameter->data()->blockSendAttributeUpdated(true);
273   theResultParameter->data()->setName(theName);
274   theResultParameter->data()->blockSendAttributeUpdated(false);
275
276   std::shared_ptr<ParametersPlugin_Parameter> aParameter = 
277       std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
278           ModelAPI_Feature::feature(theResultParameter));
279
280   aParameter->data()->blockSendAttributeUpdated(true);
281   aParameter->data()->setName(theName);
282   aParameter->string(ParametersPlugin_Parameter::VARIABLE_ID())->setValue(theName);
283   aParameter->data()->blockSendAttributeUpdated(false);
284 }
285
286 void ParametersPlugin_EvalListener::processObjectRenamedEvent(
287     const std::shared_ptr<Events_Message>& theMessage)
288 {
289   std::shared_ptr<ModelAPI_ObjectRenamedMessage> aMessage =
290       std::dynamic_pointer_cast<ModelAPI_ObjectRenamedMessage>(theMessage);
291
292   // Empty new name is not available too but it will be rejected by
293   // name validator in isValidAttribute.
294   if (!aMessage.get() || aMessage->oldName().empty())
295     return;
296
297   // check if the renamed object is a result parameter
298   ResultParameterPtr aResultParameter =
299       std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aMessage->object());
300   if (!aResultParameter.get()) 
301     return;
302
303   // get parameter feature for the result
304   std::shared_ptr<ParametersPlugin_Parameter> aParameter =
305       std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
306           ModelAPI_Feature::feature(aResultParameter));
307   if (!aParameter.get())
308     return;
309
310   // try to update the parameter feature according the new name
311   setParameterName(aResultParameter, aMessage->newName());
312   // TODO(spo): replace with ModelAPI_Session::get()->validators()->validate(aParameter, ParametersPlugin_Parameter::VARIABLE_ID())
313   // when ModelAPI_ValidatorsFactory::validate(const std::shared_ptr<ModelAPI_Feature>& theFeature, const std::string& theAttribute) const
314   // is ready
315   if (!isValidAttribute(aParameter->string(ParametersPlugin_Parameter::VARIABLE_ID()))) {
316     setParameterName(aResultParameter, aMessage->oldName());
317     return;
318   }
319
320   std::set<std::shared_ptr<ModelAPI_Attribute> > anAttributes = 
321       aResultParameter->data()->refsToMe();
322   std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator anAttributeIt =
323       anAttributes.cbegin();
324   for (; anAttributeIt != anAttributes.cend(); ++anAttributeIt) {
325     const AttributePtr& anAttribute = *anAttributeIt;
326     AttributeRefListPtr anAttributeRefList =
327         std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(anAttribute);
328     if (anAttributeRefList.get()) {
329       std::shared_ptr<ParametersPlugin_Parameter> aParameter =
330           std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
331               anAttributeRefList->owner());
332       if (aParameter.get())
333         // Rename
334         renameInParameter(aParameter, aMessage->oldName(), aMessage->newName());
335     } else
336         // Rename
337         renameInAttribute(anAttribute, aMessage->oldName(), aMessage->newName());
338   }
339 }
340