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