Salome HOME
updated copyright message
[modules/shaper.git] / src / ParametersPlugin / ParametersPlugin_EvalListener.cpp
1 // Copyright (C) 2014-2023  CEA, EDF
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::wstring toStdWString(double theValue)
55 {
56   std::wostringstream sstream;
57   sstream << theValue;
58   size_t aPos = sstream.str().find(L".");
59   std::wstring aPnt = L"";
60   if (aPos == std::wstring::npos)
61     aPnt = L".";
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::wstring ParametersPlugin_EvalListener::renameInPythonExpression(
101     const std::wstring& theExpression,
102     const std::wstring& theOldName,
103     const std::wstring& theNewName)
104 {
105   std::wstring 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(L"\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::wstring& theOldName,
143     const std::wstring& theNewName)
144 {
145   std::shared_ptr<ModelAPI_AttributeString> anExpressionAttribute =
146       theParameter->string(ParametersPlugin_Parameter::EXPRESSION_ID());
147
148   std::wstring anExpressionString = anExpressionAttribute->isUValue() ?
149       Locale::Convert::toWString(anExpressionAttribute->valueU()) :
150       Locale::Convert::toWString(anExpressionAttribute->value());
151   anExpressionString = renameInPythonExpression(anExpressionString,
152                                                 theOldName,
153                                                 theNewName);
154   // Issue #588. No need for reevaluating expression.
155   // Moreover, current history may not contain necessary parameters.
156   bool aWasBlocked = anExpressionAttribute->owner()->data()->blockSendAttributeUpdated(true);
157   anExpressionAttribute->setValue(anExpressionString);
158   anExpressionAttribute->owner()->data()->blockSendAttributeUpdated(aWasBlocked);
159 }
160
161 void ParametersPlugin_EvalListener::renameInAttribute(
162     std::shared_ptr<ModelAPI_Attribute> theAttribute,
163     const std::wstring& theOldName,
164     const std::wstring& theNewName)
165 {
166   if (theAttribute->attributeType() == ModelAPI_AttributeInteger::typeId()) {
167     AttributeIntegerPtr anAttribute =
168         std::dynamic_pointer_cast<ModelAPI_AttributeInteger>(theAttribute);
169     std::wstring anExpressionString = anAttribute->text();
170     anExpressionString = renameInPythonExpression(anExpressionString,
171                                                   theOldName, theNewName);
172     anAttribute->setText(anExpressionString);
173   } else
174   if (theAttribute->attributeType() == ModelAPI_AttributeDouble::typeId()) {
175     AttributeDoublePtr anAttribute =
176         std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theAttribute);
177     std::wstring anExpressionString = anAttribute->text();
178     anExpressionString = renameInPythonExpression(anExpressionString,
179                                                   theOldName, theNewName);
180     anAttribute->setText(anExpressionString);
181   } else
182   if (theAttribute->attributeType() == GeomDataAPI_Point::typeId()) {
183     AttributePointPtr anAttribute =
184         std::dynamic_pointer_cast<GeomDataAPI_Point>(theAttribute);
185     std::wstring anExpressionString[3] = {
186       anAttribute->textX(),
187       anAttribute->textY(),
188       anAttribute->textZ()
189     };
190     for (int i = 0; i < 3; ++i)
191       anExpressionString[i] = renameInPythonExpression(anExpressionString[i],
192                                                        theOldName, theNewName);
193     anAttribute->setText(anExpressionString[0],
194                          anExpressionString[1],
195                          anExpressionString[2]);
196   } else
197   if (theAttribute->attributeType() == GeomDataAPI_Point2D::typeId()) {
198     AttributePoint2DPtr anAttribute =
199         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute);
200     std::wstring anExpressionString[2] = {
201       anAttribute->textX(),
202       anAttribute->textY()
203     };
204     for (int i = 0; i < 2; ++i)
205       anExpressionString[i] = renameInPythonExpression(anExpressionString[i],
206                                                        theOldName, theNewName);
207     anAttribute->setText(anExpressionString[0],
208                          anExpressionString[1]);
209   }
210 }
211
212 void ParametersPlugin_EvalListener::renameInDependents(
213               std::shared_ptr<ModelAPI_ResultParameter> theResultParameter,
214               const std::wstring& theOldName,
215               const std::wstring& theNewName)
216 {
217   std::set<std::shared_ptr<ModelAPI_Attribute> > anAttributes =
218     theResultParameter->data()->refsToMe();
219   std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator anAttributeIt =
220     anAttributes.cbegin();
221   for (; anAttributeIt != anAttributes.cend(); ++anAttributeIt) {
222     const AttributePtr& anAttribute = *anAttributeIt;
223     if (anAttribute->attributeType() == ModelAPI_AttributeRefList::typeId()) {
224       std::shared_ptr<ParametersPlugin_Parameter> aParameter =
225         std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
226         anAttribute->owner());
227       if (aParameter.get())
228         // Rename
229         renameInParameter(aParameter, theOldName, theNewName);
230     } else
231       // Rename
232       renameInAttribute(anAttribute, theOldName, theNewName);
233   }
234 }
235
236 bool isValidAttribute(const AttributePtr& theAttribute)
237 {
238   std::string aValidator;
239   Events_InfoMessage anError;
240   return ModelAPI_Session::get()->validators()->validate(theAttribute, aValidator, anError);
241 }
242
243 void setParameterName(ResultParameterPtr theResultParameter, const std::string& theName)
244 {
245   bool aWasBlocked = theResultParameter->data()->blockSendAttributeUpdated(true);
246   theResultParameter->data()->setName(Locale::Convert::toWString(theName));
247   theResultParameter->data()->blockSendAttributeUpdated(aWasBlocked, false);
248
249   std::shared_ptr<ParametersPlugin_Parameter> aParameter =
250       std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
251           ModelAPI_Feature::feature(theResultParameter));
252
253   std::string anOldName = Locale::Convert::toString(aParameter->name());
254   aWasBlocked = aParameter->data()->blockSendAttributeUpdated(true);
255   aParameter->data()->setName(Locale::Convert::toWString(theName));
256   aParameter->string(ParametersPlugin_Parameter::VARIABLE_ID())->setValue(theName);
257   aParameter->data()->blockSendAttributeUpdated(aWasBlocked);
258 }
259
260 void ParametersPlugin_EvalListener::processObjectRenamedEvent(
261     const std::shared_ptr<Events_Message>& theMessage)
262 {
263   std::shared_ptr<ModelAPI_ObjectRenamedMessage> aMessage =
264       std::dynamic_pointer_cast<ModelAPI_ObjectRenamedMessage>(theMessage);
265
266   // Empty new name is not available too but it will be rejected by
267   // name validator in isValidAttribute.
268   if (!aMessage.get() || aMessage->oldName().empty())
269     return;
270
271   // check if the renamed object is a result parameter
272   ResultParameterPtr aResultParameter =
273       std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aMessage->object());
274   if (!aResultParameter.get())
275     return;
276
277   // get parameter feature for the result
278   std::shared_ptr<ParametersPlugin_Parameter> aParameter =
279       std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
280           ModelAPI_Feature::feature(aResultParameter));
281   if (!aParameter.get())
282     return;
283
284   std::wstring aNotActivatedNames;
285   if (!ModelAPI_Tools::allDocumentsActivated(aNotActivatedNames)) {
286     static const std::string aMsgContext("ParametersPlugin");
287     static const std::string aMsgText =
288       "Selected objects can be used in Part documents which are not loaded: " +
289       std::string("%1. Would you like to continue?");
290     Events_InfoMessage aMsg(aMsgContext, aMsgText);
291     aMsg.arg(aNotActivatedNames.c_str());
292     QMessageBox::StandardButton aRes =
293       QMessageBox::warning(0, ModuleBase_Tools::translate(aMsgContext, "Warning"),
294         ModuleBase_Tools::translate(aMsg),
295         QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
296     if (aRes != QMessageBox::Yes) {
297       setParameterName(aResultParameter, Locale::Convert::toString(aMessage->oldName()));
298       return;
299     }
300   }
301
302   // try to update the parameter feature according the new name
303   setParameterName(aResultParameter, Locale::Convert::toString(aMessage->newName()));
304   if (!isValidAttribute(aParameter->string(ParametersPlugin_Parameter::VARIABLE_ID()))) {
305     //setParameterName(aResultParameter, aMessage->oldName());
306     if (myOldNames.find(aParameter.get()) == myOldNames.end())
307       myOldNames[aParameter.get()] = aMessage->oldName();
308     return;
309   }
310
311   std::wstring anOldName = aMessage->oldName();
312   if (myOldNames.find(aParameter.get()) != myOldNames.end()) {
313     anOldName = myOldNames[aParameter.get()];
314     myOldNames.erase(aParameter.get());
315     aParameter->execute(); // to enable result because of previously incorrect name
316   }
317
318   renameInDependents(aResultParameter, anOldName, aMessage->newName());
319 }
320
321 void ParametersPlugin_EvalListener::processReplaceParameterEvent(
322     const std::shared_ptr<Events_Message>& theMessage)
323 {
324   std::shared_ptr<ModelAPI_ReplaceParameterMessage> aMessage =
325       std::dynamic_pointer_cast<ModelAPI_ReplaceParameterMessage>(theMessage);
326
327   // get parameter feature for the object
328   std::shared_ptr<ParametersPlugin_Parameter> aParameter =
329       std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
330           ModelAPI_Feature::feature(aMessage->object()));
331   if (!aParameter.get())
332     return;
333
334   ResultParameterPtr aResultParameter =
335       std::dynamic_pointer_cast<ModelAPI_ResultParameter>(
336           aParameter->firstResult());
337   if (!aResultParameter.get())
338     return;
339
340   double aRealValue = aResultParameter->data()->real(ModelAPI_ResultParameter::VALUE())->value();
341   std::wstring aValue = toStdWString(aRealValue);
342
343   renameInDependents(aResultParameter, aResultParameter->data()->name(), aValue);
344 }