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