Salome HOME
8e826aa1684e5db984c74e331ba6559fa4aa2129
[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 (!ModelAPI_Tools::findVariable(*it, aValue, aParamRes, theDocument)) continue;
77
78     std::ostringstream sstream;
79     sstream << aValue;
80     std::string aParamValue = sstream.str();
81     aContext.push_back(*it + "=" + aParamValue);
82   }
83   myInterp->extendLocalContext(aContext);
84   double result = myInterp->evaluate(theExpression, theError);
85   myInterp->clearLocalContext();
86   return result;
87 }
88
89 std::set<std::string> toSet(const std::list<std::string>& theContainer)
90 {
91   return std::set<std::string>(theContainer.begin(), theContainer.end());
92 }
93
94 void ParametersPlugin_EvalListener::processEvaluationEvent(
95     const std::shared_ptr<Events_Message>& theMessage)
96 {
97   std::shared_ptr<ModelAPI_AttributeEvalMessage> aMessage =
98       std::dynamic_pointer_cast<ModelAPI_AttributeEvalMessage>(theMessage);
99
100   if (aMessage->attribute()->attributeType() == ModelAPI_AttributeDouble::typeId()) {
101     AttributeDoublePtr anAttribute =
102         std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(aMessage->attribute());
103     std::string anError;
104     double aValue = evaluate(anAttribute->text(), anError, anAttribute->owner()->document());
105     bool isValid = anError.empty();
106     if (isValid)
107       anAttribute->setCalculatedValue(aValue);
108     anAttribute->setUsedParameters(isValid ? toSet(myInterp->compile(anAttribute->text())) : std::set<std::string>());
109     anAttribute->setExpressionInvalid(!isValid);
110     anAttribute->setExpressionError(anAttribute->text().empty() ? "" : anError);
111   } else
112   if (aMessage->attribute()->attributeType() == GeomDataAPI_Point::typeId()) {
113     AttributePointPtr anAttribute =
114         std::dynamic_pointer_cast<GeomDataAPI_Point>(aMessage->attribute());
115     std::string aText[] = {
116       anAttribute->textX(),
117       anAttribute->textY(),
118       anAttribute->textZ()
119     };
120     double aCalculatedValue[] = {
121       anAttribute->x(),
122       anAttribute->y(),
123       anAttribute->z()
124     };
125     for (int i = 0; i < 3; ++i) {
126       std::string anError;
127       double aValue = evaluate(aText[i], anError, anAttribute->owner()->document());
128       bool isValid = anError.empty();
129       if (isValid) aCalculatedValue[i] = aValue;
130       anAttribute->setUsedParameters(i, isValid ? toSet(myInterp->compile(aText[i])) : std::set<std::string>());
131       anAttribute->setExpressionInvalid(i, !isValid);
132       anAttribute->setExpressionError(i, aText[i].empty() ? "" : anError);
133     }
134     anAttribute->setCalculatedValue(aCalculatedValue[0],
135                                     aCalculatedValue[1],
136                                     aCalculatedValue[2]);
137   } else
138   if (aMessage->attribute()->attributeType() == GeomDataAPI_Point2D::typeId()) {
139     AttributePoint2DPtr anAttribute =
140         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aMessage->attribute());
141     std::string aText[] = {
142       anAttribute->textX(),
143       anAttribute->textY()
144     };
145     double aCalculatedValue[] = {
146       anAttribute->x(),
147       anAttribute->y()
148     };
149     for (int i = 0; i < 2; ++i) {
150       std::string anError;
151       double aValue = evaluate(aText[i], anError, anAttribute->owner()->document());
152       bool isValid = anError.empty();
153       if (isValid) aCalculatedValue[i] = aValue;
154       anAttribute->setUsedParameters(i, isValid ? toSet(myInterp->compile(aText[i])) : std::set<std::string>());
155       anAttribute->setExpressionInvalid(i, !isValid);
156       anAttribute->setExpressionError(i, aText[i].empty() ? "" : anError);
157     }
158     anAttribute->setCalculatedValue(aCalculatedValue[0],
159                                     aCalculatedValue[1]);
160   }
161 }
162
163 std::string ParametersPlugin_EvalListener::renameInPythonExpression(
164     const std::string& theExpression,
165     const std::string& theOldName,
166     const std::string& theNewName)
167 {
168   std::string anExpressionString = theExpression;
169
170   std::list<std::pair<int, int> > aPositions =
171       myInterp->positions(anExpressionString, theOldName);
172
173   if (aPositions.empty())
174     return anExpressionString;
175
176   std::map<int, std::list<int> > aLines;
177   std::list<std::pair<int, int> >::const_iterator it = aPositions.begin();
178   for (; it != aPositions.end(); ++it)
179     aLines[it->first].push_back(it->second);
180
181   // Start renaming from the end to keep indexes if theNewName is longer then theOldName
182   std::map<int, std::list<int> >::const_reverse_iterator ritLine = aLines.rbegin();
183   for (; ritLine != aLines.rend(); ++ritLine) {
184     // Calculate the start of the line (find the aLineNo occurrence of "\n" )
185     int aLineNo = ritLine->first - 1;
186     size_t aLineStart = 0;
187     for (int i = 0; i < aLineNo; ++i)
188       aLineStart = anExpressionString.find("\n", aLineStart) + 1;
189
190     const std::list<int>& aColOffsets = ritLine->second;
191     std::list<int>::const_reverse_iterator ritOffset = aColOffsets.rbegin();
192     for (; ritOffset != aColOffsets.rend(); ++ritOffset) {
193       int anOffset = *ritOffset;
194       anExpressionString.replace(aLineStart + anOffset, theOldName.size(), theNewName);
195     }
196   }
197
198   return anExpressionString;
199 }
200
201 void ParametersPlugin_EvalListener::renameInParameter(
202     std::shared_ptr<ParametersPlugin_Parameter> theParameter,
203     const std::string& theOldName,
204     const std::string& theNewName)
205 {
206   std::shared_ptr<ModelAPI_AttributeString> anExpressionAttribute =
207       theParameter->string(ParametersPlugin_Parameter::EXPRESSION_ID());
208
209   std::string anExpressionString = anExpressionAttribute->value();
210   anExpressionString = renameInPythonExpression(anExpressionString,
211                                                 theOldName,
212                                                 theNewName);
213   // Issue #588. No need for reevaluating expression. 
214   // Moreover, current history may not contain necessary parameters.
215   anExpressionAttribute->owner()->data()->blockSendAttributeUpdated(true);
216   anExpressionAttribute->setValue(anExpressionString);
217   anExpressionAttribute->owner()->data()->blockSendAttributeUpdated(false);
218 }
219
220 void ParametersPlugin_EvalListener::renameInAttribute(
221     std::shared_ptr<ModelAPI_Attribute> theAttribute,
222     const std::string& theOldName,
223     const std::string& theNewName)
224 {
225   if (theAttribute->attributeType() == ModelAPI_AttributeDouble::typeId()) {
226     AttributeDoublePtr anAttribute =
227         std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theAttribute);
228     std::string anExpressionString = anAttribute->text();
229     anExpressionString = renameInPythonExpression(anExpressionString,
230                                                   theOldName, theNewName);
231     anAttribute->setText(anExpressionString);
232   } else
233   if (theAttribute->attributeType() == GeomDataAPI_Point::typeId()) {
234     AttributePointPtr anAttribute =
235         std::dynamic_pointer_cast<GeomDataAPI_Point>(theAttribute);
236     std::string anExpressionString[3] = {
237       anAttribute->textX(),
238       anAttribute->textY(),
239       anAttribute->textZ()
240     };
241     for (int i = 0; i < 3; ++i)
242       anExpressionString[i] = renameInPythonExpression(anExpressionString[i],
243                                                        theOldName, theNewName);
244     anAttribute->setText(anExpressionString[0],
245                          anExpressionString[1],
246                          anExpressionString[2]);
247   } else
248   if (theAttribute->attributeType() == GeomDataAPI_Point2D::typeId()) {
249     AttributePoint2DPtr anAttribute =
250         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute);
251     std::string anExpressionString[2] = {
252       anAttribute->textX(),
253       anAttribute->textY()
254     };
255     for (int i = 0; i < 2; ++i)
256       anExpressionString[i] = renameInPythonExpression(anExpressionString[i],
257                                                        theOldName, theNewName);
258     anAttribute->setText(anExpressionString[0],
259                          anExpressionString[1]);
260   }
261 }
262
263 bool isValidAttribute(const AttributePtr& theAttribute)
264 {
265   std::string aValidator, anError;
266   return ModelAPI_Session::get()->validators()->validate(theAttribute, aValidator, anError);
267 }
268
269 void setParameterName(ResultParameterPtr theResultParameter, const std::string& theName)
270 {
271   theResultParameter->data()->blockSendAttributeUpdated(true);
272   theResultParameter->data()->setName(theName);
273   theResultParameter->data()->blockSendAttributeUpdated(false);
274
275   std::shared_ptr<ParametersPlugin_Parameter> aParameter = 
276       std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
277           ModelAPI_Feature::feature(theResultParameter));
278
279   aParameter->data()->blockSendAttributeUpdated(true);
280   aParameter->data()->setName(theName);
281   aParameter->string(ParametersPlugin_Parameter::VARIABLE_ID())->setValue(theName);
282   aParameter->data()->blockSendAttributeUpdated(false);
283 }
284
285 void ParametersPlugin_EvalListener::processObjectRenamedEvent(
286     const std::shared_ptr<Events_Message>& theMessage)
287 {
288   std::shared_ptr<ModelAPI_ObjectRenamedMessage> aMessage =
289       std::dynamic_pointer_cast<ModelAPI_ObjectRenamedMessage>(theMessage);
290
291   if (!aMessage.get() || aMessage->oldName().empty() || aMessage->newName().empty())
292     return;
293
294   // check if the renamed object is a result parameter
295   ResultParameterPtr aResultParameter =
296       std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aMessage->object());
297   if (!aResultParameter.get()) 
298     return;
299
300   // get parameter feature for the result
301   std::shared_ptr<ParametersPlugin_Parameter> aParameter =
302       std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
303           ModelAPI_Feature::feature(aResultParameter));
304   if (!aParameter.get())
305     return;
306
307   // try to update the parameter feature according the new name
308   setParameterName(aResultParameter, aMessage->newName());
309   // TODO(spo): replace with ModelAPI_Session::get()->validators()->validate(aParameter, ParametersPlugin_Parameter::VARIABLE_ID())
310   // when ModelAPI_ValidatorsFactory::validate(const std::shared_ptr<ModelAPI_Feature>& theFeature, const std::string& theAttribute) const
311   // is ready
312   if (!isValidAttribute(aParameter->string(ParametersPlugin_Parameter::VARIABLE_ID()))) {
313     setParameterName(aResultParameter, aMessage->oldName());
314     return;
315   }
316
317   std::set<std::shared_ptr<ModelAPI_Attribute> > anAttributes = 
318       aResultParameter->data()->refsToMe();
319   std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator anAttributeIt =
320       anAttributes.cbegin();
321   for (; anAttributeIt != anAttributes.cend(); ++anAttributeIt) {
322     const AttributePtr& anAttribute = *anAttributeIt;
323     AttributeRefListPtr anAttributeRefList =
324         std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(anAttribute);
325     if (anAttributeRefList.get()) {
326       std::shared_ptr<ParametersPlugin_Parameter> aParameter =
327           std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
328               anAttributeRefList->owner());
329       if (aParameter.get())
330         // Rename
331         renameInParameter(aParameter, aMessage->oldName(), aMessage->newName());
332     } else
333         // Rename
334         renameInAttribute(anAttribute, aMessage->oldName(), aMessage->newName());
335   }
336 }
337