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