Salome HOME
Documentation fixes.
[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::renameInDependents(std::shared_ptr<ModelAPI_ResultParameter> theResultParameter,
283                                                        const std::string& theOldName,
284                                                        const std::string& theNewName)
285 {
286   std::set<std::shared_ptr<ModelAPI_Attribute> > anAttributes =
287       theResultParameter->data()->refsToMe();
288   std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator anAttributeIt =
289       anAttributes.cbegin();
290   for (; anAttributeIt != anAttributes.cend(); ++anAttributeIt) {
291     const AttributePtr& anAttribute = *anAttributeIt;
292     if (anAttribute->attributeType() == ModelAPI_AttributeRefList::typeId()) {
293       std::shared_ptr<ParametersPlugin_Parameter> aParameter =
294           std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
295               anAttribute->owner());
296       if (aParameter.get())
297         // Rename
298         renameInParameter(aParameter, theOldName, theNewName);
299     } else
300         // Rename
301         renameInAttribute(anAttribute, theOldName, theNewName);
302   }
303 }
304
305 bool isValidAttribute(const AttributePtr& theAttribute)
306 {
307   std::string aValidator, anError;
308   return ModelAPI_Session::get()->validators()->validate(theAttribute, aValidator, anError);
309 }
310
311 void setParameterName(ResultParameterPtr theResultParameter, const std::string& theName)
312 {
313   theResultParameter->data()->blockSendAttributeUpdated(true);
314   theResultParameter->data()->setName(theName);
315   theResultParameter->data()->blockSendAttributeUpdated(false);
316
317   std::shared_ptr<ParametersPlugin_Parameter> aParameter = 
318       std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
319           ModelAPI_Feature::feature(theResultParameter));
320
321   aParameter->data()->blockSendAttributeUpdated(true);
322   aParameter->data()->setName(theName);
323   aParameter->string(ParametersPlugin_Parameter::VARIABLE_ID())->setValue(theName);
324   aParameter->data()->blockSendAttributeUpdated(false);
325 }
326
327 void ParametersPlugin_EvalListener::processObjectRenamedEvent(
328     const std::shared_ptr<Events_Message>& theMessage)
329 {
330   std::shared_ptr<ModelAPI_ObjectRenamedMessage> aMessage =
331       std::dynamic_pointer_cast<ModelAPI_ObjectRenamedMessage>(theMessage);
332
333   // Empty new name is not available too but it will be rejected by
334   // name validator in isValidAttribute.
335   if (!aMessage.get() || aMessage->oldName().empty())
336     return;
337
338   // check if the renamed object is a result parameter
339   ResultParameterPtr aResultParameter =
340       std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aMessage->object());
341   if (!aResultParameter.get()) 
342     return;
343
344   // get parameter feature for the result
345   std::shared_ptr<ParametersPlugin_Parameter> aParameter =
346       std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
347           ModelAPI_Feature::feature(aResultParameter));
348   if (!aParameter.get())
349     return;
350
351   // try to update the parameter feature according the new name
352   setParameterName(aResultParameter, aMessage->newName());
353   // TODO(spo): replace with ModelAPI_Session::get()->validators()->validate(aParameter, ParametersPlugin_Parameter::VARIABLE_ID())
354   // when ModelAPI_ValidatorsFactory::validate(const std::shared_ptr<ModelAPI_Feature>& theFeature, const std::string& theAttribute) const
355   // is ready
356   if (!isValidAttribute(aParameter->string(ParametersPlugin_Parameter::VARIABLE_ID()))) {
357     setParameterName(aResultParameter, aMessage->oldName());
358     return;
359   }
360
361   renameInDependents(aResultParameter, aMessage->oldName(), aMessage->newName());
362 }
363
364 void ParametersPlugin_EvalListener::processReplaceParameterEvent(
365     const std::shared_ptr<Events_Message>& theMessage)
366 {
367   std::shared_ptr<ModelAPI_ReplaceParameterMessage> aMessage =
368       std::dynamic_pointer_cast<ModelAPI_ReplaceParameterMessage>(theMessage);
369
370   // get parameter feature for the object
371   std::shared_ptr<ParametersPlugin_Parameter> aParameter =
372       std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
373           ModelAPI_Feature::feature(aMessage->object()));
374   if (!aParameter.get())
375     return;
376
377   ResultParameterPtr aResultParameter =
378       std::dynamic_pointer_cast<ModelAPI_ResultParameter>(
379           aParameter->firstResult());
380   if (!aResultParameter.get())
381     return;
382
383   double aRealValue = aResultParameter->data()->real(ModelAPI_ResultParameter::VALUE())->value();
384   std::string aValue = toStdString(aRealValue);
385
386   renameInDependents(aResultParameter, aResultParameter->data()->name(), aValue);
387 }