2 * ParametersPlugin_EvalListener.cpp
4 * Created on: Apr 28, 2015
10 #include <ParametersPlugin_EvalListener.h>
11 #include <ParametersPlugin_Parameter.h>
12 #include <ParametersPlugin_PyInterp.h>
14 #include <Events_InfoMessage.h>
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>
26 #include <GeomDataAPI_Point.h>
27 #include <GeomDataAPI_Point2D.h>
29 #include <QMessageBox>
35 //------------------------------------------------------------------------------
38 std::string toStdString(double theValue)
40 std::ostringstream sstream;
42 size_t aPos = sstream.str().find(".");
43 std::string aPnt = "";
44 if (aPos == std::string::npos)
46 return sstream.str() + aPnt;
49 std::set<std::string> toSet(const std::list<std::string>& theContainer)
51 return std::set<std::string>(theContainer.begin(), theContainer.end());
54 //------------------------------------------------------------------------------
56 ParametersPlugin_EvalListener::ParametersPlugin_EvalListener()
58 Events_Loop* aLoop = Events_Loop::loop();
60 Events_ID anEvents_IDs[] = {
61 ModelAPI_AttributeEvalMessage::eventId(),
62 ModelAPI_ObjectRenamedMessage::eventId(),
63 ModelAPI_ReplaceParameterMessage::eventId()
66 for (int i = 0; i < sizeof(anEvents_IDs)/sizeof(anEvents_IDs[0]); ++i)
67 aLoop->registerListener(this, anEvents_IDs[i], NULL, true);
69 myInterp = std::shared_ptr<ParametersPlugin_PyInterp>(new ParametersPlugin_PyInterp());
70 myInterp->initialize();
73 ParametersPlugin_EvalListener::~ParametersPlugin_EvalListener()
77 void ParametersPlugin_EvalListener::processEvent(
78 const std::shared_ptr<Events_Message>& theMessage)
80 if (!theMessage.get())
83 const Events_ID kEvaluationEvent = ModelAPI_AttributeEvalMessage::eventId();
84 const Events_ID kObjectRenamedEvent = ModelAPI_ObjectRenamedMessage::eventId();
85 const Events_ID kReplaceParameterEvent = ModelAPI_ReplaceParameterMessage::eventId();
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);
94 Events_InfoMessage("ParametersPlugin_EvalListener",
95 "ParametersPlugin python interpreter, unhandled message caught: ")
96 .arg(theMessage->eventID().eventText()).send();
100 double ParametersPlugin_EvalListener::evaluate(FeaturePtr theParameter,
101 const std::string& theExpression, std::string& theError)
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++) {
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()))
117 aContext.push_back(*it + "=" + toStdString(aValue));
119 myInterp->extendLocalContext(aContext);
120 double result = myInterp->evaluate(theExpression, theError);
121 myInterp->clearLocalContext();
125 void ParametersPlugin_EvalListener::processEvaluationEvent(
126 const std::shared_ptr<Events_Message>& theMessage)
128 std::shared_ptr<ModelAPI_AttributeEvalMessage> aMessage =
129 std::dynamic_pointer_cast<ModelAPI_AttributeEvalMessage>(theMessage);
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());
137 int aValue = (int)evaluate(aParamFeature, anAttribute->text(), anError);
138 bool isValid = anError.empty();
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);
145 if (aMessage->attribute()->attributeType() == ModelAPI_AttributeDouble::typeId()) {
146 AttributeDoublePtr anAttribute =
147 std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(aMessage->attribute());
149 double aValue = evaluate(aParamFeature, anAttribute->text(), anError);
150 bool isValid = anError.empty();
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);
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(),
165 double aCalculatedValue[] = {
170 for (int i = 0; i < 3; ++i) {
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);
179 anAttribute->setCalculatedValue(aCalculatedValue[0],
181 aCalculatedValue[2]);
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(),
190 double aCalculatedValue[] = {
194 for (int i = 0; i < 2; ++i) {
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);
203 anAttribute->setCalculatedValue(aCalculatedValue[0],
204 aCalculatedValue[1]);
208 std::string ParametersPlugin_EvalListener::renameInPythonExpression(
209 const std::string& theExpression,
210 const std::string& theOldName,
211 const std::string& theNewName)
213 std::string anExpressionString = theExpression;
215 std::list<std::pair<int, int> > aPositions =
216 myInterp->positions(anExpressionString, theOldName);
218 if (aPositions.empty())
219 return anExpressionString;
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);
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;
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);
243 return anExpressionString;
246 void ParametersPlugin_EvalListener::renameInParameter(
247 std::shared_ptr<ParametersPlugin_Parameter> theParameter,
248 const std::string& theOldName,
249 const std::string& theNewName)
251 std::shared_ptr<ModelAPI_AttributeString> anExpressionAttribute =
252 theParameter->string(ParametersPlugin_Parameter::EXPRESSION_ID());
254 std::string anExpressionString = anExpressionAttribute->value();
255 anExpressionString = renameInPythonExpression(anExpressionString,
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);
265 void ParametersPlugin_EvalListener::renameInAttribute(
266 std::shared_ptr<ModelAPI_Attribute> theAttribute,
267 const std::string& theOldName,
268 const std::string& theNewName)
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);
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);
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(),
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]);
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(),
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]);
316 void ParametersPlugin_EvalListener::renameInDependents(std::shared_ptr<ModelAPI_ResultParameter> theResultParameter,
317 const std::string& theOldName,
318 const std::string& theNewName)
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())
332 renameInParameter(aParameter, theOldName, theNewName);
335 renameInAttribute(anAttribute, theOldName, theNewName);
339 bool isValidAttribute(const AttributePtr& theAttribute)
341 std::string aValidator;
342 Events_InfoMessage anError;
343 return ModelAPI_Session::get()->validators()->validate(theAttribute, aValidator, anError);
346 void setParameterName(ResultParameterPtr theResultParameter, const std::string& theName)
348 theResultParameter->data()->blockSendAttributeUpdated(true);
349 theResultParameter->data()->setName(theName);
350 theResultParameter->data()->blockSendAttributeUpdated(false, false);
352 std::shared_ptr<ParametersPlugin_Parameter> aParameter =
353 std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
354 ModelAPI_Feature::feature(theResultParameter));
356 aParameter->data()->blockSendAttributeUpdated(true);
357 aParameter->data()->setName(theName);
358 aParameter->string(ParametersPlugin_Parameter::VARIABLE_ID())->setValue(theName);
359 aParameter->data()->blockSendAttributeUpdated(false);
362 void ParametersPlugin_EvalListener::processObjectRenamedEvent(
363 const std::shared_ptr<Events_Message>& theMessage)
365 std::shared_ptr<ModelAPI_ObjectRenamedMessage> aMessage =
366 std::dynamic_pointer_cast<ModelAPI_ObjectRenamedMessage>(theMessage);
368 // Empty new name is not available too but it will be rejected by
369 // name validator in isValidAttribute.
370 if (!aMessage.get() || aMessage->oldName().empty())
373 // check if the renamed object is a result parameter
374 ResultParameterPtr aResultParameter =
375 std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aMessage->object());
376 if (!aResultParameter.get())
379 // get parameter feature for the result
380 std::shared_ptr<ParametersPlugin_Parameter> aParameter =
381 std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
382 ModelAPI_Feature::feature(aResultParameter));
383 if (!aParameter.get())
386 std::string aNotActivatedNames;
387 if (!ModelAPI_Tools::allDocumentsActivated(aNotActivatedNames)) {
388 QMessageBox::StandardButton aRes = QMessageBox::warning(0, QObject::tr("Warning"),
389 QObject::tr("Selected objects can be used in Part documents which are not loaded: \
390 %1. Whould you like to continue?").arg(aNotActivatedNames.c_str()),
391 QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
392 if (aRes != QMessageBox::Yes) {
393 setParameterName(aResultParameter, aMessage->oldName());
398 // try to update the parameter feature according the new name
399 setParameterName(aResultParameter, aMessage->newName());
400 // TODO(spo): replace with ModelAPI_Session::get()->validators()->validate(aParameter, ParametersPlugin_Parameter::VARIABLE_ID())
401 // when ModelAPI_ValidatorsFactory::validate(const std::shared_ptr<ModelAPI_Feature>& theFeature, const std::string& theAttribute) const
403 if (!isValidAttribute(aParameter->string(ParametersPlugin_Parameter::VARIABLE_ID()))) {
404 setParameterName(aResultParameter, aMessage->oldName());
408 renameInDependents(aResultParameter, aMessage->oldName(), aMessage->newName());
411 void ParametersPlugin_EvalListener::processReplaceParameterEvent(
412 const std::shared_ptr<Events_Message>& theMessage)
414 std::shared_ptr<ModelAPI_ReplaceParameterMessage> aMessage =
415 std::dynamic_pointer_cast<ModelAPI_ReplaceParameterMessage>(theMessage);
417 // get parameter feature for the object
418 std::shared_ptr<ParametersPlugin_Parameter> aParameter =
419 std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
420 ModelAPI_Feature::feature(aMessage->object()));
421 if (!aParameter.get())
424 ResultParameterPtr aResultParameter =
425 std::dynamic_pointer_cast<ModelAPI_ResultParameter>(
426 aParameter->firstResult());
427 if (!aResultParameter.get())
430 double aRealValue = aResultParameter->data()->real(ModelAPI_ResultParameter::VALUE())->value();
431 std::string aValue = toStdString(aRealValue);
433 renameInDependents(aResultParameter, aResultParameter->data()->name(), aValue);