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_Error.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>
33 //------------------------------------------------------------------------------
36 std::string toStdString(double theValue)
38 std::ostringstream sstream;
40 size_t aPos = sstream.str().find(".");
41 std::string aPnt = "";
42 if (aPos == std::string::npos)
44 return sstream.str() + aPnt;
47 std::set<std::string> toSet(const std::list<std::string>& theContainer)
49 return std::set<std::string>(theContainer.begin(), theContainer.end());
52 //------------------------------------------------------------------------------
54 ParametersPlugin_EvalListener::ParametersPlugin_EvalListener()
56 Events_Loop* aLoop = Events_Loop::loop();
58 Events_ID anEvents_IDs[] = {
59 ModelAPI_AttributeEvalMessage::eventId(),
60 ModelAPI_ObjectRenamedMessage::eventId(),
61 ModelAPI_ReplaceParameterMessage::eventId()
64 for (int i = 0; i < sizeof(anEvents_IDs)/sizeof(anEvents_IDs[0]); ++i)
65 aLoop->registerListener(this, anEvents_IDs[i], NULL, true);
67 myInterp = std::shared_ptr<ParametersPlugin_PyInterp>(new ParametersPlugin_PyInterp());
68 myInterp->initialize();
71 ParametersPlugin_EvalListener::~ParametersPlugin_EvalListener()
75 void ParametersPlugin_EvalListener::processEvent(
76 const std::shared_ptr<Events_Message>& theMessage)
78 if (!theMessage.get())
81 const Events_ID kEvaluationEvent = ModelAPI_AttributeEvalMessage::eventId();
82 const Events_ID kObjectRenamedEvent = ModelAPI_ObjectRenamedMessage::eventId();
83 const Events_ID kReplaceParameterEvent = ModelAPI_ReplaceParameterMessage::eventId();
85 if (theMessage->eventID() == kEvaluationEvent) {
86 processEvaluationEvent(theMessage);
87 } else if (theMessage->eventID() == kObjectRenamedEvent) {
88 processObjectRenamedEvent(theMessage);
89 } else if (theMessage->eventID() == kReplaceParameterEvent) {
90 processReplaceParameterEvent(theMessage);
92 Events_Error::send(std::string("ParametersPlugin python interpreter, unhandled message caught: ")
93 + theMessage->eventID().eventText());
97 double ParametersPlugin_EvalListener::evaluate(FeaturePtr theParameter,
98 const std::string& theExpression, std::string& theError)
100 std::list<std::string> anExprParams = myInterp->compile(theExpression);
101 // find expression's params in the model
102 std::list<std::string> aContext;
103 std::list<std::string>::iterator it = anExprParams.begin();
104 for ( ; it != anExprParams.end(); it++) {
106 ResultParameterPtr aParamRes;
107 // If variable does not exist python interpreter will generate an error. It is OK.
108 // But due to the issue 1479 it should not check the history position of parameters relatively
109 // to feature that contains expression
110 if (!ModelAPI_Tools::findVariable(/*theParameter*/ FeaturePtr(),
111 *it, aValue, aParamRes, theParameter->document()))
114 aContext.push_back(*it + "=" + toStdString(aValue));
116 myInterp->extendLocalContext(aContext);
117 double result = myInterp->evaluate(theExpression, theError);
118 myInterp->clearLocalContext();
122 void ParametersPlugin_EvalListener::processEvaluationEvent(
123 const std::shared_ptr<Events_Message>& theMessage)
125 std::shared_ptr<ModelAPI_AttributeEvalMessage> aMessage =
126 std::dynamic_pointer_cast<ModelAPI_AttributeEvalMessage>(theMessage);
128 FeaturePtr aParamFeature =
129 std::dynamic_pointer_cast<ModelAPI_Feature>(aMessage->attribute()->owner());
130 if (aMessage->attribute()->attributeType() == ModelAPI_AttributeInteger::typeId()) {
131 AttributeIntegerPtr anAttribute =
132 std::dynamic_pointer_cast<ModelAPI_AttributeInteger>(aMessage->attribute());
134 int aValue = (int)evaluate(aParamFeature, anAttribute->text(), anError);
135 bool isValid = anError.empty();
137 anAttribute->setCalculatedValue(aValue);
138 anAttribute->setUsedParameters(isValid ? toSet(myInterp->compile(anAttribute->text())) : std::set<std::string>());
139 anAttribute->setExpressionInvalid(!isValid);
140 anAttribute->setExpressionError(anAttribute->text().empty() ? "" : anError);
142 if (aMessage->attribute()->attributeType() == ModelAPI_AttributeDouble::typeId()) {
143 AttributeDoublePtr anAttribute =
144 std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(aMessage->attribute());
146 double aValue = evaluate(aParamFeature, anAttribute->text(), anError);
147 bool isValid = anError.empty();
149 anAttribute->setCalculatedValue(aValue);
150 anAttribute->setUsedParameters(isValid ? toSet(myInterp->compile(anAttribute->text())) : std::set<std::string>());
151 anAttribute->setExpressionInvalid(!isValid);
152 anAttribute->setExpressionError(anAttribute->text().empty() ? "" : anError);
154 if (aMessage->attribute()->attributeType() == GeomDataAPI_Point::typeId()) {
155 AttributePointPtr anAttribute =
156 std::dynamic_pointer_cast<GeomDataAPI_Point>(aMessage->attribute());
157 std::string aText[] = {
158 anAttribute->textX(),
159 anAttribute->textY(),
162 double aCalculatedValue[] = {
167 for (int i = 0; i < 3; ++i) {
169 double aValue = evaluate(aParamFeature, aText[i], anError);
170 bool isValid = anError.empty();
171 if (isValid) aCalculatedValue[i] = aValue;
172 anAttribute->setUsedParameters(i, isValid ? toSet(myInterp->compile(aText[i])) : std::set<std::string>());
173 anAttribute->setExpressionInvalid(i, !isValid);
174 anAttribute->setExpressionError(i, aText[i].empty() ? "" : anError);
176 anAttribute->setCalculatedValue(aCalculatedValue[0],
178 aCalculatedValue[2]);
180 if (aMessage->attribute()->attributeType() == GeomDataAPI_Point2D::typeId()) {
181 AttributePoint2DPtr anAttribute =
182 std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aMessage->attribute());
183 std::string aText[] = {
184 anAttribute->textX(),
187 double aCalculatedValue[] = {
191 for (int i = 0; i < 2; ++i) {
193 double aValue = evaluate(aParamFeature, aText[i], anError);
194 bool isValid = anError.empty();
195 if (isValid) aCalculatedValue[i] = aValue;
196 anAttribute->setUsedParameters(i, isValid ? toSet(myInterp->compile(aText[i])) : std::set<std::string>());
197 anAttribute->setExpressionInvalid(i, !isValid);
198 anAttribute->setExpressionError(i, aText[i].empty() ? "" : anError);
200 anAttribute->setCalculatedValue(aCalculatedValue[0],
201 aCalculatedValue[1]);
205 std::string ParametersPlugin_EvalListener::renameInPythonExpression(
206 const std::string& theExpression,
207 const std::string& theOldName,
208 const std::string& theNewName)
210 std::string anExpressionString = theExpression;
212 std::list<std::pair<int, int> > aPositions =
213 myInterp->positions(anExpressionString, theOldName);
215 if (aPositions.empty())
216 return anExpressionString;
218 std::map<int, std::list<int> > aLines;
219 std::list<std::pair<int, int> >::const_iterator it = aPositions.begin();
220 for (; it != aPositions.end(); ++it)
221 aLines[it->first].push_back(it->second);
223 // Start renaming from the end to keep indexes if theNewName is longer then theOldName
224 std::map<int, std::list<int> >::const_reverse_iterator ritLine = aLines.rbegin();
225 for (; ritLine != aLines.rend(); ++ritLine) {
226 // Calculate the start of the line (find the aLineNo occurrence of "\n" )
227 int aLineNo = ritLine->first - 1;
228 size_t aLineStart = 0;
229 for (int i = 0; i < aLineNo; ++i)
230 aLineStart = anExpressionString.find("\n", aLineStart) + 1;
232 const std::list<int>& aColOffsets = ritLine->second;
233 std::list<int>::const_reverse_iterator ritOffset = aColOffsets.rbegin();
234 for (; ritOffset != aColOffsets.rend(); ++ritOffset) {
235 int anOffset = *ritOffset;
236 anExpressionString.replace(aLineStart + anOffset, theOldName.size(), theNewName);
240 return anExpressionString;
243 void ParametersPlugin_EvalListener::renameInParameter(
244 std::shared_ptr<ParametersPlugin_Parameter> theParameter,
245 const std::string& theOldName,
246 const std::string& theNewName)
248 std::shared_ptr<ModelAPI_AttributeString> anExpressionAttribute =
249 theParameter->string(ParametersPlugin_Parameter::EXPRESSION_ID());
251 std::string anExpressionString = anExpressionAttribute->value();
252 anExpressionString = renameInPythonExpression(anExpressionString,
255 // Issue #588. No need for reevaluating expression.
256 // Moreover, current history may not contain necessary parameters.
257 anExpressionAttribute->owner()->data()->blockSendAttributeUpdated(true);
258 anExpressionAttribute->setValue(anExpressionString);
259 anExpressionAttribute->owner()->data()->blockSendAttributeUpdated(false);
262 void ParametersPlugin_EvalListener::renameInAttribute(
263 std::shared_ptr<ModelAPI_Attribute> theAttribute,
264 const std::string& theOldName,
265 const std::string& theNewName)
267 if (theAttribute->attributeType() == ModelAPI_AttributeInteger::typeId()) {
268 AttributeIntegerPtr anAttribute =
269 std::dynamic_pointer_cast<ModelAPI_AttributeInteger>(theAttribute);
270 std::string anExpressionString = anAttribute->text();
271 anExpressionString = renameInPythonExpression(anExpressionString,
272 theOldName, theNewName);
273 anAttribute->setText(anExpressionString);
275 if (theAttribute->attributeType() == ModelAPI_AttributeDouble::typeId()) {
276 AttributeDoublePtr anAttribute =
277 std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theAttribute);
278 std::string anExpressionString = anAttribute->text();
279 anExpressionString = renameInPythonExpression(anExpressionString,
280 theOldName, theNewName);
281 anAttribute->setText(anExpressionString);
283 if (theAttribute->attributeType() == GeomDataAPI_Point::typeId()) {
284 AttributePointPtr anAttribute =
285 std::dynamic_pointer_cast<GeomDataAPI_Point>(theAttribute);
286 std::string anExpressionString[3] = {
287 anAttribute->textX(),
288 anAttribute->textY(),
291 for (int i = 0; i < 3; ++i)
292 anExpressionString[i] = renameInPythonExpression(anExpressionString[i],
293 theOldName, theNewName);
294 anAttribute->setText(anExpressionString[0],
295 anExpressionString[1],
296 anExpressionString[2]);
298 if (theAttribute->attributeType() == GeomDataAPI_Point2D::typeId()) {
299 AttributePoint2DPtr anAttribute =
300 std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute);
301 std::string anExpressionString[2] = {
302 anAttribute->textX(),
305 for (int i = 0; i < 2; ++i)
306 anExpressionString[i] = renameInPythonExpression(anExpressionString[i],
307 theOldName, theNewName);
308 anAttribute->setText(anExpressionString[0],
309 anExpressionString[1]);
313 void ParametersPlugin_EvalListener::renameInDependents(std::shared_ptr<ModelAPI_ResultParameter> theResultParameter,
314 const std::string& theOldName,
315 const std::string& theNewName)
317 std::set<std::shared_ptr<ModelAPI_Attribute> > anAttributes =
318 theResultParameter->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 if (anAttribute->attributeType() == ModelAPI_AttributeRefList::typeId()) {
324 std::shared_ptr<ParametersPlugin_Parameter> aParameter =
325 std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
326 anAttribute->owner());
327 if (aParameter.get())
329 renameInParameter(aParameter, theOldName, theNewName);
332 renameInAttribute(anAttribute, theOldName, theNewName);
336 bool isValidAttribute(const AttributePtr& theAttribute)
338 std::string aValidator, anError;
339 return ModelAPI_Session::get()->validators()->validate(theAttribute, aValidator, anError);
342 void setParameterName(ResultParameterPtr theResultParameter, const std::string& theName)
344 theResultParameter->data()->blockSendAttributeUpdated(true);
345 theResultParameter->data()->setName(theName);
346 theResultParameter->data()->blockSendAttributeUpdated(false);
348 std::shared_ptr<ParametersPlugin_Parameter> aParameter =
349 std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
350 ModelAPI_Feature::feature(theResultParameter));
352 aParameter->data()->blockSendAttributeUpdated(true);
353 aParameter->data()->setName(theName);
354 aParameter->string(ParametersPlugin_Parameter::VARIABLE_ID())->setValue(theName);
355 aParameter->data()->blockSendAttributeUpdated(false);
358 #include <QMessageBox>
359 #include <ModelAPI_ResultPart.h>
360 bool allDocumentsActivated(QString& theNotActivatedNames)
362 bool anAllPartActivated = true;
363 QStringList aRefNames;
365 DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
366 int aSize = aRootDoc->size(ModelAPI_ResultPart::group());
367 for (int i = 0; i < aSize; i++) {
368 ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
369 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
370 if (!aPart->isActivated()) {
371 anAllPartActivated = false;
372 aRefNames.append(aObject->data()->name().c_str());
375 theNotActivatedNames = aRefNames.join(", ");
376 return anAllPartActivated;
379 void ParametersPlugin_EvalListener::processObjectRenamedEvent(
380 const std::shared_ptr<Events_Message>& theMessage)
382 std::shared_ptr<ModelAPI_ObjectRenamedMessage> aMessage =
383 std::dynamic_pointer_cast<ModelAPI_ObjectRenamedMessage>(theMessage);
385 // Empty new name is not available too but it will be rejected by
386 // name validator in isValidAttribute.
387 if (!aMessage.get() || aMessage->oldName().empty())
390 // check if the renamed object is a result parameter
391 ResultParameterPtr aResultParameter =
392 std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aMessage->object());
393 if (!aResultParameter.get())
396 // get parameter feature for the result
397 std::shared_ptr<ParametersPlugin_Parameter> aParameter =
398 std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
399 ModelAPI_Feature::feature(aResultParameter));
400 if (!aParameter.get())
403 QString aNotActivatedNames;
404 if (!allDocumentsActivated(aNotActivatedNames)) {
405 QMessageBox::StandardButton aRes = QMessageBox::warning(0, QObject::tr("Warning"),
406 QObject::tr("Selected objects can be used in Part documents which are not loaded: \
407 %1. Whould you like to continue?").arg(aNotActivatedNames),
408 QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
409 if (aRes != QMessageBox::Yes) {
410 setParameterName(aResultParameter, aMessage->oldName());
415 // try to update the parameter feature according the new name
416 setParameterName(aResultParameter, aMessage->newName());
417 // TODO(spo): replace with ModelAPI_Session::get()->validators()->validate(aParameter, ParametersPlugin_Parameter::VARIABLE_ID())
418 // when ModelAPI_ValidatorsFactory::validate(const std::shared_ptr<ModelAPI_Feature>& theFeature, const std::string& theAttribute) const
420 if (!isValidAttribute(aParameter->string(ParametersPlugin_Parameter::VARIABLE_ID()))) {
421 setParameterName(aResultParameter, aMessage->oldName());
425 renameInDependents(aResultParameter, aMessage->oldName(), aMessage->newName());
428 void ParametersPlugin_EvalListener::processReplaceParameterEvent(
429 const std::shared_ptr<Events_Message>& theMessage)
431 std::shared_ptr<ModelAPI_ReplaceParameterMessage> aMessage =
432 std::dynamic_pointer_cast<ModelAPI_ReplaceParameterMessage>(theMessage);
434 // get parameter feature for the object
435 std::shared_ptr<ParametersPlugin_Parameter> aParameter =
436 std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
437 ModelAPI_Feature::feature(aMessage->object()));
438 if (!aParameter.get())
441 ResultParameterPtr aResultParameter =
442 std::dynamic_pointer_cast<ModelAPI_ResultParameter>(
443 aParameter->firstResult());
444 if (!aResultParameter.get())
447 double aRealValue = aResultParameter->data()->real(ModelAPI_ResultParameter::VALUE())->value();
448 std::string aValue = toStdString(aRealValue);
450 renameInDependents(aResultParameter, aResultParameter->data()->name(), aValue);