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