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