]> SALOME platform Git repositories - modules/shaper.git/blob - src/ParametersPlugin/ParametersPlugin_EvalListener.cpp
Salome HOME
Issue #1505 Bug in parameters management (with parts not loaded)
[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   size_t aPos = sstream.str().find(".");
41   std::string aPnt = "";
42   if (aPos == std::string::npos)
43     aPnt = ".";
44   return sstream.str() + aPnt;
45 }
46
47 std::set<std::string> toSet(const std::list<std::string>& theContainer)
48 {
49   return std::set<std::string>(theContainer.begin(), theContainer.end());
50 }
51
52 //------------------------------------------------------------------------------
53
54 ParametersPlugin_EvalListener::ParametersPlugin_EvalListener()
55 {
56   Events_Loop* aLoop = Events_Loop::loop();
57
58   Events_ID anEvents_IDs[] = {
59       ModelAPI_AttributeEvalMessage::eventId(),
60       ModelAPI_ObjectRenamedMessage::eventId(),
61       ModelAPI_ReplaceParameterMessage::eventId()
62   };
63
64   for (int i = 0; i < sizeof(anEvents_IDs)/sizeof(anEvents_IDs[0]); ++i)
65     aLoop->registerListener(this, anEvents_IDs[i], NULL, true);
66
67   myInterp = std::shared_ptr<ParametersPlugin_PyInterp>(new ParametersPlugin_PyInterp());
68   myInterp->initialize();
69 }
70
71 ParametersPlugin_EvalListener::~ParametersPlugin_EvalListener()
72 {
73 }
74
75 void ParametersPlugin_EvalListener::processEvent(
76     const std::shared_ptr<Events_Message>& theMessage)
77 {
78   if (!theMessage.get())
79     return;
80
81   const Events_ID kEvaluationEvent = ModelAPI_AttributeEvalMessage::eventId();
82   const Events_ID kObjectRenamedEvent = ModelAPI_ObjectRenamedMessage::eventId();
83   const Events_ID kReplaceParameterEvent = ModelAPI_ReplaceParameterMessage::eventId();
84
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);
91   } else {
92     Events_Error::send(std::string("ParametersPlugin python interpreter, unhandled message caught: ")
93                        + theMessage->eventID().eventText());
94   }
95 }
96
97 double ParametersPlugin_EvalListener::evaluate(FeaturePtr theParameter,
98   const std::string& theExpression, std::string& theError)
99 {
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++) {
105     double aValue;
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()))
112       continue;
113
114     aContext.push_back(*it + "=" + toStdString(aValue));
115   }
116   myInterp->extendLocalContext(aContext);
117   double result = myInterp->evaluate(theExpression, theError);
118   myInterp->clearLocalContext();
119   return result;
120 }
121
122 void ParametersPlugin_EvalListener::processEvaluationEvent(
123     const std::shared_ptr<Events_Message>& theMessage)
124 {
125   std::shared_ptr<ModelAPI_AttributeEvalMessage> aMessage =
126       std::dynamic_pointer_cast<ModelAPI_AttributeEvalMessage>(theMessage);
127
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());
133     std::string anError;
134     int aValue = (int)evaluate(aParamFeature, anAttribute->text(), anError);
135     bool isValid = anError.empty();
136     if (isValid)
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);
141   } else
142   if (aMessage->attribute()->attributeType() == ModelAPI_AttributeDouble::typeId()) {
143     AttributeDoublePtr anAttribute =
144         std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(aMessage->attribute());
145     std::string anError;
146     double aValue = evaluate(aParamFeature, anAttribute->text(), anError);
147     bool isValid = anError.empty();
148     if (isValid)
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);
153   } else
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(),
160       anAttribute->textZ()
161     };
162     double aCalculatedValue[] = {
163       anAttribute->x(),
164       anAttribute->y(),
165       anAttribute->z()
166     };
167     for (int i = 0; i < 3; ++i) {
168       std::string anError;
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);
175     }
176     anAttribute->setCalculatedValue(aCalculatedValue[0],
177                                     aCalculatedValue[1],
178                                     aCalculatedValue[2]);
179   } else
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(),
185       anAttribute->textY()
186     };
187     double aCalculatedValue[] = {
188       anAttribute->x(),
189       anAttribute->y()
190     };
191     for (int i = 0; i < 2; ++i) {
192       std::string anError;
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);
199     }
200     anAttribute->setCalculatedValue(aCalculatedValue[0],
201                                     aCalculatedValue[1]);
202   }
203 }
204
205 std::string ParametersPlugin_EvalListener::renameInPythonExpression(
206     const std::string& theExpression,
207     const std::string& theOldName,
208     const std::string& theNewName)
209 {
210   std::string anExpressionString = theExpression;
211
212   std::list<std::pair<int, int> > aPositions =
213       myInterp->positions(anExpressionString, theOldName);
214
215   if (aPositions.empty())
216     return anExpressionString;
217
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);
222
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;
231
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);
237     }
238   }
239
240   return anExpressionString;
241 }
242
243 void ParametersPlugin_EvalListener::renameInParameter(
244     std::shared_ptr<ParametersPlugin_Parameter> theParameter,
245     const std::string& theOldName,
246     const std::string& theNewName)
247 {
248   std::shared_ptr<ModelAPI_AttributeString> anExpressionAttribute =
249       theParameter->string(ParametersPlugin_Parameter::EXPRESSION_ID());
250
251   std::string anExpressionString = anExpressionAttribute->value();
252   anExpressionString = renameInPythonExpression(anExpressionString,
253                                                 theOldName,
254                                                 theNewName);
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);
260 }
261
262 void ParametersPlugin_EvalListener::renameInAttribute(
263     std::shared_ptr<ModelAPI_Attribute> theAttribute,
264     const std::string& theOldName,
265     const std::string& theNewName)
266 {
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);
274   } else
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);
282   } else
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(),
289       anAttribute->textZ()
290     };
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]);
297   } else
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(),
303       anAttribute->textY()
304     };
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]);
310   }
311 }
312
313 void ParametersPlugin_EvalListener::renameInDependents(std::shared_ptr<ModelAPI_ResultParameter> theResultParameter,
314                                                        const std::string& theOldName,
315                                                        const std::string& theNewName)
316 {
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())
328         // Rename
329         renameInParameter(aParameter, theOldName, theNewName);
330     } else
331         // Rename
332         renameInAttribute(anAttribute, theOldName, theNewName);
333   }
334 }
335
336 bool isValidAttribute(const AttributePtr& theAttribute)
337 {
338   std::string aValidator, anError;
339   return ModelAPI_Session::get()->validators()->validate(theAttribute, aValidator, anError);
340 }
341
342 void setParameterName(ResultParameterPtr theResultParameter, const std::string& theName)
343 {
344   theResultParameter->data()->blockSendAttributeUpdated(true);
345   theResultParameter->data()->setName(theName);
346   theResultParameter->data()->blockSendAttributeUpdated(false);
347
348   std::shared_ptr<ParametersPlugin_Parameter> aParameter = 
349       std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
350           ModelAPI_Feature::feature(theResultParameter));
351
352   aParameter->data()->blockSendAttributeUpdated(true);
353   aParameter->data()->setName(theName);
354   aParameter->string(ParametersPlugin_Parameter::VARIABLE_ID())->setValue(theName);
355   aParameter->data()->blockSendAttributeUpdated(false);
356 }
357
358 #include <QMessageBox>
359 #include <ModelAPI_ResultPart.h>
360 bool allDocumentsActivated(QString& theNotActivatedNames)
361 {
362   bool anAllPartActivated = true;
363   QStringList aRefNames;
364
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());
373     }
374   }
375   theNotActivatedNames = aRefNames.join(", ");
376   return anAllPartActivated;
377 }
378
379 void ParametersPlugin_EvalListener::processObjectRenamedEvent(
380     const std::shared_ptr<Events_Message>& theMessage)
381 {
382   std::shared_ptr<ModelAPI_ObjectRenamedMessage> aMessage =
383       std::dynamic_pointer_cast<ModelAPI_ObjectRenamedMessage>(theMessage);
384
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())
388     return;
389
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()) 
394     return;
395
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())
401     return;
402
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());
411       return;
412     }
413   }
414
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
419   // is ready
420   if (!isValidAttribute(aParameter->string(ParametersPlugin_Parameter::VARIABLE_ID()))) {
421     setParameterName(aResultParameter, aMessage->oldName());
422     return;
423   }
424
425   renameInDependents(aResultParameter, aMessage->oldName(), aMessage->newName());
426 }
427
428 void ParametersPlugin_EvalListener::processReplaceParameterEvent(
429     const std::shared_ptr<Events_Message>& theMessage)
430 {
431   std::shared_ptr<ModelAPI_ReplaceParameterMessage> aMessage =
432       std::dynamic_pointer_cast<ModelAPI_ReplaceParameterMessage>(theMessage);
433
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())
439     return;
440
441   ResultParameterPtr aResultParameter =
442       std::dynamic_pointer_cast<ModelAPI_ResultParameter>(
443           aParameter->firstResult());
444   if (!aResultParameter.get())
445     return;
446
447   double aRealValue = aResultParameter->data()->real(ModelAPI_ResultParameter::VALUE())->value();
448   std::string aValue = toStdString(aRealValue);
449
450   renameInDependents(aResultParameter, aResultParameter->data()->name(), aValue);
451 }