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