Salome HOME
Merge remote-tracking branch 'remotes/origin/EDF_2020_Lot2'
[modules/shaper.git] / src / ParametersPlugin / ParametersPlugin_EvalListener.cpp
1 // Copyright (C) 2014-2020  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include <pyconfig.h>
21
22 #include <ParametersPlugin_EvalListener.h>
23 #include <ParametersPlugin_Parameter.h>
24
25 #include <Events_InfoMessage.h>
26
27 #include <Locale_Convert.h>
28
29 #include <ModelAPI_AttributeDouble.h>
30 #include <ModelAPI_AttributeInteger.h>
31 #include <ModelAPI_AttributeRefList.h>
32 #include <ModelAPI_AttributeString.h>
33 #include <ModelAPI_AttributeValidator.h>
34 #include <ModelAPI_Document.h>
35 #include <ModelAPI_Events.h>
36 #include <ModelAPI_ResultParameter.h>
37 #include <ModelAPI_Session.h>
38 #include <ModelAPI_Tools.h>
39
40 #include <GeomDataAPI_Point.h>
41 #include <GeomDataAPI_Point2D.h>
42
43 #include <QMessageBox>
44
45 #include <ModuleBase_Tools.h>
46
47 #include <string>
48 #include <set>
49 #include <sstream>
50
51 //------------------------------------------------------------------------------
52 // Tools
53
54 static std::string toStdString(double theValue)
55 {
56   std::ostringstream sstream;
57   sstream << theValue;
58   size_t aPos = sstream.str().find(".");
59   std::string aPnt = "";
60   if (aPos == std::string::npos)
61     aPnt = ".";
62   return sstream.str() + aPnt;
63 }
64
65 //------------------------------------------------------------------------------
66
67 ParametersPlugin_EvalListener::ParametersPlugin_EvalListener()
68 {
69   Events_Loop* aLoop = Events_Loop::loop();
70
71   Events_ID anEvents_IDs[] = {
72       ModelAPI_ObjectRenamedMessage::eventId(),
73       ModelAPI_ReplaceParameterMessage::eventId()
74   };
75
76   for (unsigned long long i = 0; i < sizeof(anEvents_IDs)/sizeof(anEvents_IDs[0]); ++i)
77     aLoop->registerListener(this, anEvents_IDs[i], NULL, true);
78 }
79
80 ParametersPlugin_EvalListener::~ParametersPlugin_EvalListener()
81 {
82 }
83
84 void ParametersPlugin_EvalListener::processEvent(
85     const std::shared_ptr<Events_Message>& theMessage)
86 {
87   if (!theMessage.get())
88     return;
89
90   const Events_ID kObjectRenamedEvent = ModelAPI_ObjectRenamedMessage::eventId();
91   const Events_ID kReplaceParameterEvent = ModelAPI_ReplaceParameterMessage::eventId();
92
93   if (theMessage->eventID() == kObjectRenamedEvent) {
94     processObjectRenamedEvent(theMessage);
95   } else if (theMessage->eventID() == kReplaceParameterEvent) {
96     processReplaceParameterEvent(theMessage);
97   }
98 }
99
100 std::string ParametersPlugin_EvalListener::renameInPythonExpression(
101     const std::string& theExpression,
102     const std::string& theOldName,
103     const std::string& theNewName)
104 {
105   std::string anExpressionString = theExpression;
106
107   // ask interpreter to compute the positions in the expression
108   std::shared_ptr<ModelAPI_ComputePositionsMessage> aMsg =
109     ModelAPI_ComputePositionsMessage::send(theExpression, theOldName, this);
110   const std::list<std::pair<int, int> >& aPositions = aMsg->positions();
111
112   if (aPositions.empty())
113     return anExpressionString;
114
115   std::map<int, std::list<int> > aLines;
116   std::list<std::pair<int, int> >::const_iterator it = aPositions.begin();
117   for (; it != aPositions.end(); ++it)
118     aLines[it->first].push_back(it->second);
119
120   // Start renaming from the end to keep indexes if theNewName is longer then theOldName
121   std::map<int, std::list<int> >::const_reverse_iterator ritLine = aLines.rbegin();
122   for (; ritLine != aLines.rend(); ++ritLine) {
123     // Calculate the start of the line (find the aLineNo occurrence of "\n" )
124     int aLineNo = ritLine->first - 1;
125     size_t aLineStart = 0;
126     for (int i = 0; i < aLineNo; ++i)
127       aLineStart = anExpressionString.find("\n", aLineStart) + 1;
128
129     const std::list<int>& aColOffsets = ritLine->second;
130     std::list<int>::const_reverse_iterator ritOffset = aColOffsets.rbegin();
131     for (; ritOffset != aColOffsets.rend(); ++ritOffset) {
132       int anOffset = *ritOffset;
133       anExpressionString.replace(aLineStart + anOffset, theOldName.size(), theNewName);
134     }
135   }
136
137   return anExpressionString;
138 }
139
140 void ParametersPlugin_EvalListener::renameInParameter(
141     std::shared_ptr<ParametersPlugin_Parameter> theParameter,
142     const std::string& theOldName,
143     const std::string& theNewName)
144 {
145   std::shared_ptr<ModelAPI_AttributeString> anExpressionAttribute =
146       theParameter->string(ParametersPlugin_Parameter::EXPRESSION_ID());
147
148   std::string anExpressionString = anExpressionAttribute->value();
149   anExpressionString = renameInPythonExpression(anExpressionString,
150                                                 theOldName,
151                                                 theNewName);
152   // Issue #588. No need for reevaluating expression.
153   // Moreover, current history may not contain necessary parameters.
154   bool aWasBlocked = anExpressionAttribute->owner()->data()->blockSendAttributeUpdated(true);
155   anExpressionAttribute->setValue(anExpressionString);
156   anExpressionAttribute->owner()->data()->blockSendAttributeUpdated(aWasBlocked);
157 }
158
159 void ParametersPlugin_EvalListener::renameInAttribute(
160     std::shared_ptr<ModelAPI_Attribute> theAttribute,
161     const std::string& theOldName,
162     const std::string& theNewName)
163 {
164   if (theAttribute->attributeType() == ModelAPI_AttributeInteger::typeId()) {
165     AttributeIntegerPtr anAttribute =
166         std::dynamic_pointer_cast<ModelAPI_AttributeInteger>(theAttribute);
167     std::string anExpressionString = anAttribute->text();
168     anExpressionString = renameInPythonExpression(anExpressionString,
169                                                   theOldName, theNewName);
170     anAttribute->setText(anExpressionString);
171   } else
172   if (theAttribute->attributeType() == ModelAPI_AttributeDouble::typeId()) {
173     AttributeDoublePtr anAttribute =
174         std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theAttribute);
175     std::string anExpressionString = anAttribute->text();
176     anExpressionString = renameInPythonExpression(anExpressionString,
177                                                   theOldName, theNewName);
178     anAttribute->setText(anExpressionString);
179   } else
180   if (theAttribute->attributeType() == GeomDataAPI_Point::typeId()) {
181     AttributePointPtr anAttribute =
182         std::dynamic_pointer_cast<GeomDataAPI_Point>(theAttribute);
183     std::string anExpressionString[3] = {
184       anAttribute->textX(),
185       anAttribute->textY(),
186       anAttribute->textZ()
187     };
188     for (int i = 0; i < 3; ++i)
189       anExpressionString[i] = renameInPythonExpression(anExpressionString[i],
190                                                        theOldName, theNewName);
191     anAttribute->setText(anExpressionString[0],
192                          anExpressionString[1],
193                          anExpressionString[2]);
194   } else
195   if (theAttribute->attributeType() == GeomDataAPI_Point2D::typeId()) {
196     AttributePoint2DPtr anAttribute =
197         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute);
198     std::string anExpressionString[2] = {
199       anAttribute->textX(),
200       anAttribute->textY()
201     };
202     for (int i = 0; i < 2; ++i)
203       anExpressionString[i] = renameInPythonExpression(anExpressionString[i],
204                                                        theOldName, theNewName);
205     anAttribute->setText(anExpressionString[0],
206                          anExpressionString[1]);
207   }
208 }
209
210 void ParametersPlugin_EvalListener::renameInDependents(
211               std::shared_ptr<ModelAPI_ResultParameter> theResultParameter,
212               const std::string& theOldName,
213               const std::string& theNewName)
214 {
215   std::set<std::shared_ptr<ModelAPI_Attribute> > anAttributes =
216     theResultParameter->data()->refsToMe();
217   std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator anAttributeIt =
218     anAttributes.cbegin();
219   for (; anAttributeIt != anAttributes.cend(); ++anAttributeIt) {
220     const AttributePtr& anAttribute = *anAttributeIt;
221     if (anAttribute->attributeType() == ModelAPI_AttributeRefList::typeId()) {
222       std::shared_ptr<ParametersPlugin_Parameter> aParameter =
223         std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
224         anAttribute->owner());
225       if (aParameter.get())
226         // Rename
227         renameInParameter(aParameter, theOldName, theNewName);
228     } else
229       // Rename
230       renameInAttribute(anAttribute, theOldName, theNewName);
231   }
232 }
233
234 bool isValidAttribute(const AttributePtr& theAttribute)
235 {
236   std::string aValidator;
237   Events_InfoMessage anError;
238   return ModelAPI_Session::get()->validators()->validate(theAttribute, aValidator, anError);
239 }
240
241 void setParameterName(ResultParameterPtr theResultParameter, const std::string& theName)
242 {
243   bool aWasBlocked = theResultParameter->data()->blockSendAttributeUpdated(true);
244   theResultParameter->data()->setName(Locale::Convert::toWString(theName));
245   theResultParameter->data()->blockSendAttributeUpdated(aWasBlocked, false);
246
247   std::shared_ptr<ParametersPlugin_Parameter> aParameter =
248       std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
249           ModelAPI_Feature::feature(theResultParameter));
250
251   std::string anOldName = Locale::Convert::toString(aParameter->name());
252   aWasBlocked = aParameter->data()->blockSendAttributeUpdated(true);
253   aParameter->data()->setName(Locale::Convert::toWString(theName));
254   aParameter->string(ParametersPlugin_Parameter::VARIABLE_ID())->setValue(theName);
255   aParameter->data()->blockSendAttributeUpdated(aWasBlocked);
256 }
257
258 void ParametersPlugin_EvalListener::processObjectRenamedEvent(
259     const std::shared_ptr<Events_Message>& theMessage)
260 {
261   std::shared_ptr<ModelAPI_ObjectRenamedMessage> aMessage =
262       std::dynamic_pointer_cast<ModelAPI_ObjectRenamedMessage>(theMessage);
263
264   // Empty new name is not available too but it will be rejected by
265   // name validator in isValidAttribute.
266   if (!aMessage.get() || aMessage->oldName().empty())
267     return;
268
269   // check if the renamed object is a result parameter
270   ResultParameterPtr aResultParameter =
271       std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aMessage->object());
272   if (!aResultParameter.get())
273     return;
274
275   // get parameter feature for the result
276   std::shared_ptr<ParametersPlugin_Parameter> aParameter =
277       std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
278           ModelAPI_Feature::feature(aResultParameter));
279   if (!aParameter.get())
280     return;
281
282   std::wstring aNotActivatedNames;
283   if (!ModelAPI_Tools::allDocumentsActivated(aNotActivatedNames)) {
284     static const std::string aMsgContext("ParametersPlugin");
285     static const std::string aMsgText =
286       "Selected objects can be used in Part documents which are not loaded: " +
287       std::string("%1. Would you like to continue?");
288     Events_InfoMessage aMsg(aMsgContext, aMsgText);
289     aMsg.arg(aNotActivatedNames.c_str());
290     QMessageBox::StandardButton aRes =
291       QMessageBox::warning(0, ModuleBase_Tools::translate(aMsgContext, "Warning"),
292         ModuleBase_Tools::translate(aMsg),
293         QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
294     if (aRes != QMessageBox::Yes) {
295       setParameterName(aResultParameter, Locale::Convert::toString(aMessage->oldName()));
296       return;
297     }
298   }
299
300   // try to update the parameter feature according the new name
301   setParameterName(aResultParameter, Locale::Convert::toString(aMessage->newName()));
302   if (!isValidAttribute(aParameter->string(ParametersPlugin_Parameter::VARIABLE_ID()))) {
303     //setParameterName(aResultParameter, aMessage->oldName());
304     if (myOldNames.find(aParameter.get()) == myOldNames.end())
305       myOldNames[aParameter.get()] = Locale::Convert::toString(aMessage->oldName());
306     return;
307   }
308
309   std::string anOldName = Locale::Convert::toString(aMessage->oldName());
310   if (myOldNames.find(aParameter.get()) != myOldNames.end()) {
311     anOldName = myOldNames[aParameter.get()];
312     myOldNames.erase(aParameter.get());
313     aParameter->execute(); // to enable result because of previously incorrect name
314   }
315
316   renameInDependents(aResultParameter, anOldName,
317                      Locale::Convert::toString(aMessage->newName()));
318 }
319
320 void ParametersPlugin_EvalListener::processReplaceParameterEvent(
321     const std::shared_ptr<Events_Message>& theMessage)
322 {
323   std::shared_ptr<ModelAPI_ReplaceParameterMessage> aMessage =
324       std::dynamic_pointer_cast<ModelAPI_ReplaceParameterMessage>(theMessage);
325
326   // get parameter feature for the object
327   std::shared_ptr<ParametersPlugin_Parameter> aParameter =
328       std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
329           ModelAPI_Feature::feature(aMessage->object()));
330   if (!aParameter.get())
331     return;
332
333   ResultParameterPtr aResultParameter =
334       std::dynamic_pointer_cast<ModelAPI_ResultParameter>(
335           aParameter->firstResult());
336   if (!aResultParameter.get())
337     return;
338
339   double aRealValue = aResultParameter->data()->real(ModelAPI_ResultParameter::VALUE())->value();
340   std::string aValue = toStdString(aRealValue);
341
342   renameInDependents(aResultParameter,
343                      Locale::Convert::toString(aResultParameter->data()->name()),
344                      aValue);
345 }