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