Salome HOME
[bos #29933] [CEA 29931] Redundant constraint in SHAPER SIGSEGV
[modules/shaper.git] / src / PartSet / PartSet_OverconstraintListener.cpp
1 // Copyright (C) 2014-2021  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 <ModelAPI_Tools.h>
21 #include <ModelAPI_AttributeString.h>
22
23 // Attention: keep the next include here,
24 // otherwise it causes compilation errors at least on Debian 8
25 #include <ModuleBase_Preferences.h>
26
27 #include "PartSet_OverconstraintListener.h"
28 #include <PartSet_Module.h>
29 #include <PartSet_SketcherMgr.h>
30 #include <PartSet_SketcherReentrantMgr.h>
31
32 #include "XGUI_Displayer.h"
33 #include "XGUI_ModuleConnector.h"
34 #include "XGUI_OperationMgr.h"
35 #include "XGUI_Tools.h"
36 #include "XGUI_Workshop.h"
37
38 #include "SketcherPrs_SymbolPrs.h"
39 #include "SketchPlugin_SketchEntity.h"
40 #include "SketchPlugin_MacroArcReentrantMessage.h"
41 #include "SketchPlugin_Sketch.h"
42 #include "SketchPlugin_ConstraintHorizontal.h"
43 #include "SketchPlugin_ConstraintVertical.h"
44
45 #include <SUIT_ResourceMgr.h>
46
47 #include "Events_Loop.h"
48
49 #include <GeomAPI_IPresentable.h>
50 #include <ModelAPI_Events.h>
51 #include <ModelAPI_EventReentrantMessage.h>
52 #include <ModuleBase_Tools.h>
53
54 #include <QString>
55 #include <QTimer>
56
57 //#define DEBUG_FEATURE_OVERCONSTRAINT_LISTENER
58
59 PartSet_OverconstraintListener::PartSet_OverconstraintListener(ModuleBase_IWorkshop* theWorkshop)
60 : myWorkshop(theWorkshop), myIsActive(false), myIsFullyConstrained(false)
61 {
62   Events_Loop* aLoop = Events_Loop::loop();
63   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_SOLVER_FAILED));
64   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_SOLVER_REPAIRED));
65
66   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_SKETCH_UNDER_CONSTRAINED));
67   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_SKETCH_FULLY_CONSTRAINED));
68
69   aLoop->registerListener(this, ModelAPI_EventReentrantMessage::eventId());
70   aLoop->registerListener(this, SketchPlugin_MacroArcReentrantMessage::eventId());
71   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_REMOVE_CONSTRAINTS));
72 }
73
74 void PartSet_OverconstraintListener::setActive(const bool& theActive)
75 {
76   if (myIsActive == theActive)
77     return;
78
79   myIsActive = theActive;
80   myIsFullyConstrained = false; /// returned to default state, no custom color for it
81
82   if (myIsActive) {
83     PartSet_Module* aModule = module();
84     CompositeFeaturePtr aSketch = aModule->sketchMgr()->activeSketch();
85     if (aSketch.get()) {
86       QString aDOFMessage(aSketch->string(SketchPlugin_Sketch::SOLVER_DOF())->value().c_str());
87       if (aDOFMessage.contains('=')) {
88         // to support old data
89         aDOFMessage =
90           aDOFMessage.right(aDOFMessage.length() - aDOFMessage.lastIndexOf('=')).trimmed();
91       }
92       myIsFullyConstrained = (aDOFMessage == "0");
93     }
94   }
95 }
96
97 void PartSet_OverconstraintListener::getCustomColor(const ObjectPtr& theObject,
98                                                     std::vector<int>& theColor)
99 {
100   if (!myIsActive)
101     return;
102
103   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
104
105   if (myConflictingObjects.find(theObject) != myConflictingObjects.end()) {
106     theColor = Config_PropManager::color("Visualization", "sketch_overconstraint_color");
107   }
108   if (myIsFullyConstrained) {
109     // only entity features has custom color when sketch is fully constrained
110     if (aFeature.get() && PartSet_SketcherMgr::isEntity(aFeature->getKind()) &&
111         !PartSet_SketcherMgr::isExternalFeature(aFeature)) {
112       PartSet_Module* aModule = module();
113       CompositeFeaturePtr aSketch = aModule->sketchMgr()->activeSketch();
114       // the given object is sub feature of the current sketch(created or edited)
115       if (ModelAPI_Tools::compositeOwner(aFeature) == aSketch)
116         theColor = Config_PropManager::color("Visualization", "sketch_fully_constrained_color");
117     }
118   }
119 }
120
121 void PartSet_OverconstraintListener::processEvent(const std::shared_ptr<Events_Message>& theMessage)
122 {
123   // #2271 open document: if sketch has confilcting elements, solver sends message with the
124   // elements by opening the document. Sketch is not active, but an internal container should
125   // be updated. So, we should not check whether the listener is active here
126   //if (!myIsActive)
127   //  return;
128
129 #ifdef DEBUG_FEATURE_OVERCONSTRAINT_LISTENER
130   bool isRepaired = theMessage->eventID() == Events_Loop::eventByName(EVENT_SOLVER_REPAIRED);
131   int aCount = 0;
132
133   std::shared_ptr<ModelAPI_SolverFailedMessage> anErrorMsg =
134                   std::dynamic_pointer_cast<ModelAPI_SolverFailedMessage>(theMessage);
135   QString anInfoStr;
136   if (anErrorMsg.get()) {
137     const std::set<ObjectPtr>& aConflictingObjects = anErrorMsg->objects();
138     aCount = aConflictingObjects.size();
139     anInfoStr = getObjectsInfo(aConflictingObjects);
140   }
141
142   QString aCurrentInfoStr = getObjectsInfo(myConflictingObjects);
143
144   QString aMsg("PartSet_OverconstraintListener::processEvent: %1,\nobjects "
145                "count = %2:%3\ncurrent objects count = %4:%5");
146   qDebug(aMsg.arg(isRepaired ? "REPAIRED" : "FAILED")
147              .arg(aCount).arg(anInfoStr).arg(myConflictingObjects.size())
148              .arg(aCurrentInfoStr).toStdString().c_str());
149 #endif
150
151   Events_ID anEventID = theMessage->eventID();
152   if (anEventID == Events_Loop::eventByName(EVENT_SOLVER_FAILED) ||
153       anEventID == Events_Loop::eventByName(EVENT_SOLVER_REPAIRED)) {
154     std::shared_ptr<ModelAPI_SolverFailedMessage> anErrorMsg =
155                    std::dynamic_pointer_cast<ModelAPI_SolverFailedMessage>(theMessage);
156     if (anErrorMsg.get()) {
157       const std::set<ObjectPtr>& aConflictingObjects = anErrorMsg->objects();
158       if (anEventID == Events_Loop::eventByName(EVENT_SOLVER_FAILED))
159         appendConflictingObjects(aConflictingObjects);
160       else
161         repairConflictingObjects(aConflictingObjects);
162     }
163   }
164   else if (anEventID == Events_Loop::eventByName(EVENT_SKETCH_UNDER_CONSTRAINED) ||
165            anEventID == Events_Loop::eventByName(EVENT_SKETCH_FULLY_CONSTRAINED)) {
166     bool aPrevFullyConstrained = myIsFullyConstrained;
167     myIsFullyConstrained = anEventID == Events_Loop::eventByName(EVENT_SKETCH_FULLY_CONSTRAINED);
168
169     if (aPrevFullyConstrained != myIsFullyConstrained) {
170       std::set<ObjectPtr> aModifiedObjects;
171       PartSet_Module* aModule = dynamic_cast<PartSet_Module*>(myWorkshop->module());
172       CompositeFeaturePtr aSketch = aModule->sketchMgr()->activeSketch();
173
174       // check the sketch in the message and the active sketch are the same
175       std::shared_ptr<ModelAPI_SolverFailedMessage> anErrorMsg =
176           std::dynamic_pointer_cast<ModelAPI_SolverFailedMessage>(theMessage);
177       if (aSketch && anErrorMsg && !anErrorMsg->objects().empty()) {
178         ObjectPtr anObject = *anErrorMsg->objects().begin();
179         CompositeFeaturePtr aSketchFromMsg =
180             std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(anObject);
181         if (!aSketchFromMsg || aSketchFromMsg != aSketch)
182           aSketch = CompositeFeaturePtr();
183       }
184
185       if (aSketch.get()) {
186         int aNumberOfSubs = aSketch->numberOfSubs();
187         for (int i = 0; i < aNumberOfSubs; i++) {
188           FeaturePtr aFeature = aSketch->subFeature(i);
189           aModifiedObjects.insert(aFeature); // is necessary to redisplay presentations
190           std::list<ResultPtr> aResults = aFeature->results();
191           for (std::list<ResultPtr>::const_iterator aIt = aResults.begin();
192                aIt != aResults.end(); ++aIt) {
193             aModifiedObjects.insert(*aIt);
194           }
195         }
196         redisplayObjects(aModifiedObjects);
197       }
198     }
199   }
200   else if (anEventID == ModelAPI_EventReentrantMessage::eventId() ||
201            anEventID == SketchPlugin_MacroArcReentrantMessage::eventId()) {
202     // the message is sent to sketcher reentrant manager only if the name of feature
203     // sender is equal to feature name of the current operation. E.g. Horizontal create operation
204     // is active. Sketch Line feature is changed, so execute is called, it will send message
205     // This Line's message should not be processed, as the reentrant operation is not for Line
206     // It is not enoght of kind, the name should be used, e.g. restarted Lines on auxiliary
207     // cirlce sometimes causes previous line change, kind the same, but feature line is different
208     std::wstring aCurrentFeatureName;
209     ModuleBase_Operation* anOperation =
210                 XGUI_Tools::workshop(myWorkshop)->operationMgr()->currentOperation();
211     if (anOperation) {
212       ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
213                                                            (anOperation);
214       if (aFOperation) {
215         FeaturePtr aFeature = aFOperation->feature();
216         // data valid is necessary if the feature has been already deleted
217         // (e.g. Esc of Lenght if lenght value is modified)
218         if (aFeature.get() && aFeature->data()->isValid())
219           aCurrentFeatureName = aFeature->data()->name();
220       }
221     }
222     if (theMessage->sender()) {
223       ModelAPI_Object* aSender = static_cast<ModelAPI_Object*>(theMessage->sender());
224       if (aSender) {
225         FeaturePtr aFeatureSender =
226           std::dynamic_pointer_cast<ModelAPI_Feature>(aSender->data()->owner());
227         if (aFeatureSender.get() && aFeatureSender->data()->name() == aCurrentFeatureName) {
228           PartSet_Module* aModule = dynamic_cast<PartSet_Module*>(myWorkshop->module());
229           PartSet_SketcherReentrantMgr* aReentrantMgr = aModule->sketchReentranceMgr();
230           aReentrantMgr->setReentrantMessage(theMessage);
231         }
232       }
233     }
234   }
235   else if (anEventID == Events_Loop::eventByName(EVENT_REMOVE_CONSTRAINTS)) {
236     std::shared_ptr<ModelAPI_CheckConstraintsMessage> aConstraintsMsg =
237       std::dynamic_pointer_cast<ModelAPI_CheckConstraintsMessage>(theMessage);
238     if (aConstraintsMsg.get()) {
239       myObjectsToRemove = aConstraintsMsg->constraints();
240
241       std::set<ObjectPtr>::const_iterator anIt = myObjectsToRemove.begin();
242
243       PartSet_Module* aModule = dynamic_cast<PartSet_Module*>(myWorkshop->module());
244
245       for (; anIt != myObjectsToRemove.end(); )
246       {
247         ObjectPtr anObject = *anIt;
248         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
249         std::string aType = aFeature->getKind();
250         if ((aType == SketchPlugin_ConstraintHorizontal::ID() ||
251              aType == SketchPlugin_ConstraintVertical::ID()) &&
252              !aModule->sketchReentranceMgr()->isLastAutoConstraint(*anIt))
253           anIt = myObjectsToRemove.erase(anIt);
254         else
255           anIt++;
256       }
257
258       if (myObjectsToRemove.empty())
259         return;
260
261       QTimer::singleShot(5, aModule, SLOT(onRemoveConflictingConstraints()));
262     }
263   }
264 #ifdef DEBUG_FEATURE_OVERCONSTRAINT_LISTENER
265   aCurrentInfoStr = getObjectsInfo(myConflictingObjects);
266   qDebug(QString("RESULT: current objects count = %1:%2\n")
267                 .arg(myConflictingObjects.size()).arg(aCurrentInfoStr).toStdString().c_str());
268 #endif
269 }
270
271 bool PartSet_OverconstraintListener::appendConflictingObjects(
272                                                const std::set<ObjectPtr>& theConflictingObjects)
273 {
274   bool isAllowToChange = ModuleBase_Preferences::resourceMgr()->booleanValue(SKETCH_TAB_NAME,
275                                         "allow_change_constraint");
276   if (isAllowToChange) {
277     std::set<ObjectPtr> aModifiedObjects;
278
279     // set error state for new objects and append them in the internal map of objects
280     std::set<ObjectPtr>::const_iterator
281       anIt = theConflictingObjects.begin(), aLast = theConflictingObjects.end();
282
283     int aCountOfSimilarConstraints = 0;
284     for (; anIt != aLast; anIt++) {
285       ObjectPtr anObject = *anIt;
286       if (myConflictingObjects.find(anObject) == myConflictingObjects.end()) { // it is not found
287         aModifiedObjects.insert(anObject);
288         myConflictingObjects.insert(anObject);
289       }
290       else
291         ++aCountOfSimilarConstraints;
292     }
293
294     if (theConflictingObjects.size() == aCountOfSimilarConstraints)
295       return false;
296
297     std::shared_ptr<ModelAPI_CheckConstraintsMessage> aMessage =
298       std::shared_ptr<ModelAPI_CheckConstraintsMessage>(
299         new ModelAPI_CheckConstraintsMessage(
300           Events_Loop::eventByName(EVENT_CHECK_CONSTRAINTS)));
301     aMessage->setConstraints(theConflictingObjects);
302     Events_Loop::loop()->send(aMessage);
303
304     bool isUpdated = !aModifiedObjects.empty();
305     if (isUpdated)
306       redisplayObjects(aModifiedObjects);
307     return isUpdated;
308   }
309   else
310     return false;
311 }
312
313 bool PartSet_OverconstraintListener::repairConflictingObjects(
314                                               const std::set<ObjectPtr>& theConflictingObjects)
315 {
316   std::set<ObjectPtr> aModifiedObjects;
317   // erase error state of absent current objects in the parameter list
318   std::set<ObjectPtr>::const_iterator anIt, aLast;
319   for (anIt = theConflictingObjects.begin(), aLast = theConflictingObjects.end();
320        anIt != aLast; anIt++) {
321     ObjectPtr anObject = *anIt;
322     if (theConflictingObjects.find(anObject) != theConflictingObjects.end()) { // it is found
323       myConflictingObjects.erase(anObject);
324       aModifiedObjects.insert(anObject);
325     }
326   }
327   bool isUpdated = !aModifiedObjects.empty();
328   if (isUpdated)
329     redisplayObjects(aModifiedObjects);
330
331   return isUpdated;
332 }
333
334 void PartSet_OverconstraintListener::redisplayObjects(
335                                               const std::set<ObjectPtr>& theObjects)
336 {
337   static Events_Loop* aLoop = Events_Loop::loop();
338
339   static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_VISUAL_ATTRIBUTES);
340   static Events_ID EVENT_REDISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
341   static const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
342
343   std::set<ObjectPtr>::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
344   for (; anIt != aLast; anIt++) {
345     ObjectPtr aObj = *anIt;
346     aECreator->sendUpdated(aObj, EVENT_DISP);
347     aECreator->sendUpdated(aObj, EVENT_REDISP);
348   }
349   aLoop->flush(EVENT_DISP);
350   aLoop->flush(EVENT_REDISP);
351 }
352
353 PartSet_Module* PartSet_OverconstraintListener::module() const
354 {
355   return dynamic_cast<PartSet_Module*>(myWorkshop->module());
356 }
357
358 #ifdef _DEBUG
359 QString PartSet_OverconstraintListener::getObjectsInfo(const std::set<ObjectPtr>& theObjects)
360 {
361   std::set<ObjectPtr>::const_iterator anIt = theObjects.begin(),
362                                       aLast = theObjects.end();
363   QStringList anInfo;
364   for (; anIt != aLast; ++anIt)
365     anInfo.append(ModuleBase_Tools::objectInfo((*anIt)));
366
367   return anInfo.join(";\n");
368 }
369 #endif