Salome HOME
Merge remote-tracking branch 'origin/Toolbars_Management'
[modules/shaper.git] / src / ParametersPlugin / ParametersPlugin_EvalListener.cpp
1 // Copyright (C) 2014-2017  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
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include <pyconfig.h>
22
23 #include <ParametersPlugin_EvalListener.h>
24 #include <ParametersPlugin_Parameter.h>
25
26 #include <Events_InfoMessage.h>
27
28 #include <ModelAPI_AttributeDouble.h>
29 #include <ModelAPI_AttributeInteger.h>
30 #include <ModelAPI_AttributeRefList.h>
31 #include <ModelAPI_AttributeString.h>
32 #include <ModelAPI_AttributeValidator.h>
33 #include <ModelAPI_Document.h>
34 #include <ModelAPI_Events.h>
35 #include <ModelAPI_ResultParameter.h>
36 #include <ModelAPI_Session.h>
37 #include <ModelAPI_Tools.h>
38
39 #include <GeomDataAPI_Point.h>
40 #include <GeomDataAPI_Point2D.h>
41
42 #include <QMessageBox>
43
44 #include <string>
45 #include <set>
46 #include <sstream>
47
48 //------------------------------------------------------------------------------
49 // Tools
50
51 static std::string toStdString(double theValue)
52 {
53   std::ostringstream sstream;
54   sstream << theValue;
55   size_t aPos = sstream.str().find(".");
56   std::string aPnt = "";
57   if (aPos == std::string::npos)
58     aPnt = ".";
59   return sstream.str() + aPnt;
60 }
61
62 static std::set<std::string> toSet(const std::list<std::string>& theContainer)
63 {
64   return std::set<std::string>(theContainer.begin(), theContainer.end());
65 }
66
67 //------------------------------------------------------------------------------
68
69 ParametersPlugin_EvalListener::ParametersPlugin_EvalListener()
70 {
71   Events_Loop* aLoop = Events_Loop::loop();
72
73   Events_ID anEvents_IDs[] = {
74       ModelAPI_ObjectRenamedMessage::eventId(),
75       ModelAPI_ReplaceParameterMessage::eventId()
76   };
77
78   for (int i = 0; i < sizeof(anEvents_IDs)/sizeof(anEvents_IDs[0]); ++i)
79     aLoop->registerListener(this, anEvents_IDs[i], NULL, true);
80 }
81
82 ParametersPlugin_EvalListener::~ParametersPlugin_EvalListener()
83 {
84 }
85
86 void ParametersPlugin_EvalListener::processEvent(
87     const std::shared_ptr<Events_Message>& theMessage)
88 {
89   if (!theMessage.get())
90     return;
91
92   const Events_ID kObjectRenamedEvent = ModelAPI_ObjectRenamedMessage::eventId();
93   const Events_ID kReplaceParameterEvent = ModelAPI_ReplaceParameterMessage::eventId();
94
95   if (theMessage->eventID() == kObjectRenamedEvent) {
96     processObjectRenamedEvent(theMessage);
97   } else if (theMessage->eventID() == kReplaceParameterEvent) {
98     processReplaceParameterEvent(theMessage);
99   }
100 }
101
102 std::string ParametersPlugin_EvalListener::renameInPythonExpression(
103     const std::string& theExpression,
104     const std::string& theOldName,
105     const std::string& theNewName)
106 {
107   std::string anExpressionString = theExpression;
108
109   // ask interpreter to compute the positions in the expression
110   std::shared_ptr<ModelAPI_ComputePositionsMessage> aMsg =
111     ModelAPI_ComputePositionsMessage::send(theExpression, theOldName, this);
112   const std::list<std::pair<int, int> >& aPositions = aMsg->positions();
113
114   if (aPositions.empty())
115     return anExpressionString;
116
117   std::map<int, std::list<int> > aLines;
118   std::list<std::pair<int, int> >::const_iterator it = aPositions.begin();
119   for (; it != aPositions.end(); ++it)
120     aLines[it->first].push_back(it->second);
121
122   // Start renaming from the end to keep indexes if theNewName is longer then theOldName
123   std::map<int, std::list<int> >::const_reverse_iterator ritLine = aLines.rbegin();
124   for (; ritLine != aLines.rend(); ++ritLine) {
125     // Calculate the start of the line (find the aLineNo occurrence of "\n" )
126     int aLineNo = ritLine->first - 1;
127     size_t aLineStart = 0;
128     for (int i = 0; i < aLineNo; ++i)
129       aLineStart = anExpressionString.find("\n", aLineStart) + 1;
130
131     const std::list<int>& aColOffsets = ritLine->second;
132     std::list<int>::const_reverse_iterator ritOffset = aColOffsets.rbegin();
133     for (; ritOffset != aColOffsets.rend(); ++ritOffset) {
134       int anOffset = *ritOffset;
135       anExpressionString.replace(aLineStart + anOffset, theOldName.size(), theNewName);
136     }
137   }
138
139   return anExpressionString;
140 }
141
142 void ParametersPlugin_EvalListener::renameInParameter(
143     std::shared_ptr<ParametersPlugin_Parameter> theParameter,
144     const std::string& theOldName,
145     const std::string& theNewName)
146 {
147   std::shared_ptr<ModelAPI_AttributeString> anExpressionAttribute =
148       theParameter->string(ParametersPlugin_Parameter::EXPRESSION_ID());
149
150   std::string anExpressionString = 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::string& theOldName,
164     const std::string& theNewName)
165 {
166   if (theAttribute->attributeType() == ModelAPI_AttributeInteger::typeId()) {
167     AttributeIntegerPtr anAttribute =
168         std::dynamic_pointer_cast<ModelAPI_AttributeInteger>(theAttribute);
169     std::string 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::string 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::string 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::string 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::string& theOldName,
215               const std::string& 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(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 = aParameter->name();
254   aWasBlocked = aParameter->data()->blockSendAttributeUpdated(true);
255   aParameter->data()->setName(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::string aNotActivatedNames;
285   if (!ModelAPI_Tools::allDocumentsActivated(aNotActivatedNames)) {
286     QMessageBox::StandardButton aRes = QMessageBox::warning(0, QObject::tr("Warning"),
287                QObject::tr("Selected objects can be used in Part documents which are not loaded: "
288                            "%1. Whould you like to continue?").arg(aNotActivatedNames.c_str()),
289                QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
290     if (aRes != QMessageBox::Yes) {
291       setParameterName(aResultParameter, aMessage->oldName());
292       return;
293     }
294   }
295
296   // try to update the parameter feature according the new name
297   setParameterName(aResultParameter, aMessage->newName());
298   if (!isValidAttribute(aParameter->string(ParametersPlugin_Parameter::VARIABLE_ID()))) {
299     //setParameterName(aResultParameter, aMessage->oldName());
300     if (myOldNames.find(aParameter.get()) == myOldNames.end())
301       myOldNames[aParameter.get()] = aMessage->oldName();
302     return;
303   }
304
305   std::string anOldName = aMessage->oldName();
306   if (myOldNames.find(aParameter.get()) != myOldNames.end()) {
307     anOldName = myOldNames[aParameter.get()];
308     myOldNames.erase(aParameter.get());
309     aParameter->execute(); // to enable result because of previously incorrect name
310   }
311
312   renameInDependents(aResultParameter, anOldName, aMessage->newName());
313 }
314
315 void ParametersPlugin_EvalListener::processReplaceParameterEvent(
316     const std::shared_ptr<Events_Message>& theMessage)
317 {
318   std::shared_ptr<ModelAPI_ReplaceParameterMessage> aMessage =
319       std::dynamic_pointer_cast<ModelAPI_ReplaceParameterMessage>(theMessage);
320
321   // get parameter feature for the object
322   std::shared_ptr<ParametersPlugin_Parameter> aParameter =
323       std::dynamic_pointer_cast<ParametersPlugin_Parameter>(
324           ModelAPI_Feature::feature(aMessage->object()));
325   if (!aParameter.get())
326     return;
327
328   ResultParameterPtr aResultParameter =
329       std::dynamic_pointer_cast<ModelAPI_ResultParameter>(
330           aParameter->firstResult());
331   if (!aResultParameter.get())
332     return;
333
334   double aRealValue = aResultParameter->data()->real(ModelAPI_ResultParameter::VALUE())->value();
335   std::string aValue = toStdString(aRealValue);
336
337   renameInDependents(aResultParameter, aResultParameter->data()->name(), aValue);
338 }