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