Salome HOME
Merge remote-tracking branch 'origin/SALOME-8.2.0_porting'
[modules/shaper.git] / src / ParametersPlugin / ParametersPlugin_EvalListener.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D -->
2 /*
3  * ParametersPlugin_EvalListener.cpp
4  *
5  *  Created on: Apr 28, 2015
6  *      Author: sbh
7  */
8
9 #include <pyconfig.h>
10
11 #include <ParametersPlugin_EvalListener.h>
12 #include <ParametersPlugin_Parameter.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_ObjectRenamedMessage::eventId(),
62       ModelAPI_ReplaceParameterMessage::eventId()
63   };
64
65   for (int i = 0; i < sizeof(anEvents_IDs)/sizeof(anEvents_IDs[0]); ++i)
66     aLoop->registerListener(this, anEvents_IDs[i], NULL, true);
67 }
68
69 ParametersPlugin_EvalListener::~ParametersPlugin_EvalListener()
70 {
71 }
72
73 void ParametersPlugin_EvalListener::processEvent(
74     const std::shared_ptr<Events_Message>& theMessage)
75 {
76   if (!theMessage.get())
77     return;
78
79   const Events_ID kObjectRenamedEvent = ModelAPI_ObjectRenamedMessage::eventId();
80   const Events_ID kReplaceParameterEvent = ModelAPI_ReplaceParameterMessage::eventId();
81
82   if (theMessage->eventID() == kObjectRenamedEvent) {
83     processObjectRenamedEvent(theMessage);
84   } else if (theMessage->eventID() == kReplaceParameterEvent) {
85     processReplaceParameterEvent(theMessage);
86   }
87 }
88
89 std::string ParametersPlugin_EvalListener::renameInPythonExpression(
90     const std::string& theExpression,
91     const std::string& theOldName,
92     const std::string& theNewName)
93 {
94   std::string anExpressionString = theExpression;
95
96   // ask interpreter to compute the positions in the expression
97   std::shared_ptr<ModelAPI_ComputePositionsMessage> aMsg =
98     ModelAPI_ComputePositionsMessage::send(theExpression, theOldName, this);
99   const std::list<std::pair<int, int> >& aPositions = aMsg->positions();
100
101   if (aPositions.empty())
102     return anExpressionString;
103
104   std::map<int, std::list<int> > aLines;
105   std::list<std::pair<int, int> >::const_iterator it = aPositions.begin();
106   for (; it != aPositions.end(); ++it)
107     aLines[it->first].push_back(it->second);
108
109   // Start renaming from the end to keep indexes if theNewName is longer then theOldName
110   std::map<int, std::list<int> >::const_reverse_iterator ritLine = aLines.rbegin();
111   for (; ritLine != aLines.rend(); ++ritLine) {
112     // Calculate the start of the line (find the aLineNo occurrence of "\n" )
113     int aLineNo = ritLine->first - 1;
114     size_t aLineStart = 0;
115     for (int i = 0; i < aLineNo; ++i)
116       aLineStart = anExpressionString.find("\n", aLineStart) + 1;
117
118     const std::list<int>& aColOffsets = ritLine->second;
119     std::list<int>::const_reverse_iterator ritOffset = aColOffsets.rbegin();
120     for (; ritOffset != aColOffsets.rend(); ++ritOffset) {
121       int anOffset = *ritOffset;
122       anExpressionString.replace(aLineStart + anOffset, theOldName.size(), theNewName);
123     }
124   }
125
126   return anExpressionString;
127 }
128
129 void ParametersPlugin_EvalListener::renameInParameter(
130     std::shared_ptr<ParametersPlugin_Parameter> theParameter,
131     const std::string& theOldName,
132     const std::string& theNewName)
133 {
134   std::shared_ptr<ModelAPI_AttributeString> anExpressionAttribute =
135       theParameter->string(ParametersPlugin_Parameter::EXPRESSION_ID());
136
137   std::string anExpressionString = anExpressionAttribute->value();
138   anExpressionString = renameInPythonExpression(anExpressionString,
139                                                 theOldName,
140                                                 theNewName);
141   // Issue #588. No need for reevaluating expression.
142   // Moreover, current history may not contain necessary parameters.
143   anExpressionAttribute->owner()->data()->blockSendAttributeUpdated(true);
144   anExpressionAttribute->setValue(anExpressionString);
145   anExpressionAttribute->owner()->data()->blockSendAttributeUpdated(false);
146 }
147
148 void ParametersPlugin_EvalListener::renameInAttribute(
149     std::shared_ptr<ModelAPI_Attribute> theAttribute,
150     const std::string& theOldName,
151     const std::string& theNewName)
152 {
153   if (theAttribute->attributeType() == ModelAPI_AttributeInteger::typeId()) {
154     AttributeIntegerPtr anAttribute =
155         std::dynamic_pointer_cast<ModelAPI_AttributeInteger>(theAttribute);
156     std::string anExpressionString = anAttribute->text();
157     anExpressionString = renameInPythonExpression(anExpressionString,
158                                                   theOldName, theNewName);
159     anAttribute->setText(anExpressionString);
160   } else
161   if (theAttribute->attributeType() == ModelAPI_AttributeDouble::typeId()) {
162     AttributeDoublePtr anAttribute =
163         std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theAttribute);
164     std::string anExpressionString = anAttribute->text();
165     anExpressionString = renameInPythonExpression(anExpressionString,
166                                                   theOldName, theNewName);
167     anAttribute->setText(anExpressionString);
168   } else
169   if (theAttribute->attributeType() == GeomDataAPI_Point::typeId()) {
170     AttributePointPtr anAttribute =
171         std::dynamic_pointer_cast<GeomDataAPI_Point>(theAttribute);
172     std::string anExpressionString[3] = {
173       anAttribute->textX(),
174       anAttribute->textY(),
175       anAttribute->textZ()
176     };
177     for (int i = 0; i < 3; ++i)
178       anExpressionString[i] = renameInPythonExpression(anExpressionString[i],
179                                                        theOldName, theNewName);
180     anAttribute->setText(anExpressionString[0],
181                          anExpressionString[1],
182                          anExpressionString[2]);
183   } else
184   if (theAttribute->attributeType() == GeomDataAPI_Point2D::typeId()) {
185     AttributePoint2DPtr anAttribute =
186         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute);
187     std::string anExpressionString[2] = {
188       anAttribute->textX(),
189       anAttribute->textY()
190     };
191     for (int i = 0; i < 2; ++i)
192       anExpressionString[i] = renameInPythonExpression(anExpressionString[i],
193                                                        theOldName, theNewName);
194     anAttribute->setText(anExpressionString[0],
195                          anExpressionString[1]);
196   }
197 }
198
199 void ParametersPlugin_EvalListener::renameInDependents(
200               std::shared_ptr<ModelAPI_ResultParameter> theResultParameter,
201               const std::string& theOldName,
202               const std::string& theNewName)
203 {
204   std::set<std::shared_ptr<ModelAPI_Attribute> > anAttributes =
205     theResultParameter->data()->refsToMe();
206   std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator anAttributeIt =
207     anAttributes.cbegin();
208   for (; anAttributeIt != anAttributes.cend(); ++anAttributeIt) {
209     const AttributePtr& anAttribute = *anAttributeIt;
210     if (anAttribute->attributeType() == ModelAPI_AttributeRefList::typeId()) {
211       std::shared_ptr<ParametersPlugin_Parameter> aParameter =
212         std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
213         anAttribute->owner());
214       if (aParameter.get())
215         // Rename
216         renameInParameter(aParameter, theOldName, theNewName);
217     } else
218       // Rename
219       renameInAttribute(anAttribute, theOldName, theNewName);
220   }
221 }
222
223 bool isValidAttribute(const AttributePtr& theAttribute)
224 {
225   std::string aValidator;
226   Events_InfoMessage anError;
227   return ModelAPI_Session::get()->validators()->validate(theAttribute, aValidator, anError);
228 }
229
230 void setParameterName(ResultParameterPtr theResultParameter, const std::string& theName)
231 {
232   theResultParameter->data()->blockSendAttributeUpdated(true);
233   theResultParameter->data()->setName(theName);
234   theResultParameter->data()->blockSendAttributeUpdated(false, false);
235
236   std::shared_ptr<ParametersPlugin_Parameter> aParameter =
237       std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
238           ModelAPI_Feature::feature(theResultParameter));
239
240   aParameter->data()->blockSendAttributeUpdated(true);
241   aParameter->data()->setName(theName);
242   aParameter->string(ParametersPlugin_Parameter::VARIABLE_ID())->setValue(theName);
243   aParameter->data()->blockSendAttributeUpdated(false);
244 }
245
246 void ParametersPlugin_EvalListener::processObjectRenamedEvent(
247     const std::shared_ptr<Events_Message>& theMessage)
248 {
249   std::shared_ptr<ModelAPI_ObjectRenamedMessage> aMessage =
250       std::dynamic_pointer_cast<ModelAPI_ObjectRenamedMessage>(theMessage);
251
252   // Empty new name is not available too but it will be rejected by
253   // name validator in isValidAttribute.
254   if (!aMessage.get() || aMessage->oldName().empty())
255     return;
256
257   // check if the renamed object is a result parameter
258   ResultParameterPtr aResultParameter =
259       std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aMessage->object());
260   if (!aResultParameter.get())
261     return;
262
263   // get parameter feature for the result
264   std::shared_ptr<ParametersPlugin_Parameter> aParameter =
265       std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
266           ModelAPI_Feature::feature(aResultParameter));
267   if (!aParameter.get())
268     return;
269
270   std::string aNotActivatedNames;
271   if (!ModelAPI_Tools::allDocumentsActivated(aNotActivatedNames)) {
272     QMessageBox::StandardButton aRes = QMessageBox::warning(0, QObject::tr("Warning"),
273                QObject::tr("Selected objects can be used in Part documents which are not loaded: "
274                            "%1. Whould you like to continue?").arg(aNotActivatedNames.c_str()),
275                QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
276     if (aRes != QMessageBox::Yes) {
277       setParameterName(aResultParameter, aMessage->oldName());
278       return;
279     }
280   }
281
282   // try to update the parameter feature according the new name
283   setParameterName(aResultParameter, aMessage->newName());
284   if (!isValidAttribute(aParameter->string(ParametersPlugin_Parameter::VARIABLE_ID()))) {
285     //setParameterName(aResultParameter, aMessage->oldName());
286     if (myOldNames.find(aParameter.get()) == myOldNames.end())
287       myOldNames[aParameter.get()] = aMessage->oldName();
288     return;
289   }
290
291   std::string anOldName = aMessage->oldName();
292   if (myOldNames.find(aParameter.get()) != myOldNames.end()) {
293     anOldName = myOldNames[aParameter.get()];
294     myOldNames.erase(aParameter.get());
295     aParameter->execute(); // to enable result because of previously incorrect name
296   }
297
298   renameInDependents(aResultParameter, anOldName, aMessage->newName());
299 }
300
301 void ParametersPlugin_EvalListener::processReplaceParameterEvent(
302     const std::shared_ptr<Events_Message>& theMessage)
303 {
304   std::shared_ptr<ModelAPI_ReplaceParameterMessage> aMessage =
305       std::dynamic_pointer_cast<ModelAPI_ReplaceParameterMessage>(theMessage);
306
307   // get parameter feature for the object
308   std::shared_ptr<ParametersPlugin_Parameter> aParameter =
309       std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
310           ModelAPI_Feature::feature(aMessage->object()));
311   if (!aParameter.get())
312     return;
313
314   ResultParameterPtr aResultParameter =
315       std::dynamic_pointer_cast<ModelAPI_ResultParameter>(
316           aParameter->firstResult());
317   if (!aResultParameter.get())
318     return;
319
320   double aRealValue = aResultParameter->data()->real(ModelAPI_ResultParameter::VALUE())->value();
321   std::string aValue = toStdString(aRealValue);
322
323   renameInDependents(aResultParameter, aResultParameter->data()->name(), aValue);
324 }