Salome HOME
Copyright update 2022
[modules/shaper.git] / src / ModuleBase / ModuleBase_WidgetValidated.cpp
1 // Copyright (C) 2014-2022  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 <ModuleBase_WidgetValidated.h>
21 #include <ModuleBase_IModule.h>
22 #include <ModuleBase_IViewer.h>
23 #include <ModuleBase_IWorkshop.h>
24 #include <ModuleBase_ISelection.h>
25 #include <ModuleBase_ISelectionActivate.h>
26 #include <ModuleBase_WidgetSelectorStore.h>
27 #include <ModuleBase_ViewerPrs.h>
28
29 #include <Events_InfoMessage.h>
30
31 #include <ModelAPI_Session.h>
32 #include <ModelAPI_Validator.h>
33 #include <ModelAPI_AttributeValidator.h>
34 #include <ModelAPI_Events.h>
35 #include <ModelAPI_Tools.h>
36 #include <ModelAPI_AttributeSelection.h>
37
38 #include <SelectMgr_ListIteratorOfListOfFilter.hxx>
39 #include <SelectMgr_EntityOwner.hxx>
40 #include <StdSelect_BRepOwner.hxx>
41
42 #include <Events_Loop.h>
43
44 #include <QWidget>
45
46 //#define DEBUG_VALID_STATE
47
48 ModuleBase_WidgetValidated::ModuleBase_WidgetValidated(QWidget* theParent,
49                                                        ModuleBase_IWorkshop* theWorkshop,
50                                                        const Config_WidgetAPI* theData)
51 : ModuleBase_ModelWidget(theParent, theData),
52   myWorkshop(theWorkshop), myIsInValidate(false)
53 {
54   myAttributeStore = new ModuleBase_WidgetSelectorStore();
55 }
56
57 ModuleBase_WidgetValidated::~ModuleBase_WidgetValidated()
58 {
59   delete myAttributeStore;
60 }
61
62 //********************************************************************
63 ObjectPtr ModuleBase_WidgetValidated::findPresentedObject(const AISObjectPtr& theAIS) const
64 {
65   return myPresentedObject;
66 }
67
68 //********************************************************************
69 void ModuleBase_WidgetValidated::deactivate()
70 {
71   clearValidatedCash();
72 }
73
74 //********************************************************************
75 void ModuleBase_WidgetValidated::clearValidatedCash()
76 {
77 #ifdef DEBUG_VALID_STATE
78   qDebug("clearValidatedCash");
79 #endif
80   myValidPrs.Clear();
81   myInvalidPrs.Clear();
82 }
83
84 //********************************************************************
85 void ModuleBase_WidgetValidated::storeAttributeValue(const AttributePtr& theAttribute)
86 {
87   myIsInValidate = true;
88   myAttributeStore->storeAttributeValue(theAttribute, myWorkshop);
89 }
90
91 //********************************************************************
92 void ModuleBase_WidgetValidated::restoreAttributeValue(const AttributePtr& theAttribute,
93                                                        const bool theValid)
94 {
95   myIsInValidate = false;
96   myAttributeStore->restoreAttributeValue(theAttribute, myWorkshop);
97 }
98
99
100 //********************************************************************
101 void ModuleBase_WidgetValidated::collectSubBodies(const ResultBodyPtr& theBody,
102                                                   AIS_NListOfEntityOwner& theList)
103 {
104   AISObjectPtr aIOPtr;
105   TopoDS_Shape aTDShape;
106   int aNb = theBody->numberOfSubs();
107   for (int i = 0; i < aNb; i++) {
108     ResultBodyPtr aSub = theBody->subResult(i);
109     if (aSub->numberOfSubs() > 0)
110       collectSubBodies(aSub, theList);
111     else {
112       aTDShape = aSub->shape()->impl<TopoDS_Shape>();
113       aIOPtr = myWorkshop->findPresentation(aSub);
114       if (aIOPtr.get()) {
115         Handle(AIS_InteractiveObject) anIO = aIOPtr->impl<Handle(AIS_InteractiveObject)>();
116         theList.Append(new StdSelect_BRepOwner(aTDShape, anIO));
117       }
118       else
119         theList.Append(new StdSelect_BRepOwner(aTDShape));
120     }
121   }
122 }
123
124 //********************************************************************
125 bool ModuleBase_WidgetValidated::isValidInFilters(const ModuleBase_ViewerPrsPtr& thePrs)
126 {
127   bool aValid = true;
128   AIS_NListOfEntityOwner aOwnersList;
129   if (!thePrs->owner().IsNull())
130     aOwnersList.Append(thePrs->owner());
131
132   // if an owner is null, the selection happens in the Object browser.
133   // creates a selection owner on the base of object shape and the object AIS object
134   if ((aOwnersList.Size() == 0) && thePrs->object().get()) {
135     ResultPtr aResult = myWorkshop->selection()->getResult(thePrs);
136     GeomShapePtr aShape = aResult.get() ? aResult->shape() : GeomShapePtr();
137     // some results have no shape, e.g. the parameter one. So, they should not be validated
138     if (aShape.get()) {
139       const TopoDS_Shape aTDShape = aShape->impl<TopoDS_Shape>();
140       Handle(AIS_InteractiveObject) anIO = myWorkshop->selection()->getIO(thePrs);
141       aOwnersList.Append(new StdSelect_BRepOwner(aTDShape, anIO));
142       myPresentedObject = aResult;
143     }
144     else {
145       //FeaturePtr aFeature = ModelAPI_Feature::feature(thePrs->object());
146       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(thePrs->object());
147       if (aFeature.get()) {
148         // Use feature as a reference to all its results
149         myPresentedObject = aFeature;
150         AttributePtr anAttr = attribute();
151         std::string aType = anAttr->attributeType();
152
153         // Check that results of Feature is acceptable by filters for selection attribute
154         if (aType == ModelAPI_AttributeSelection::typeId()) {
155           AttributeSelectionPtr aSelectAttr =
156             std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(anAttr);
157           aSelectAttr->setValue(myPresentedObject, GeomShapePtr(), true);
158           GeomShapePtr aShapePtr = aSelectAttr->value();
159           if (!aShapePtr.get() && aSelectAttr->contextFeature().get() &&
160             aSelectAttr->contextFeature()->firstResult().get()) {
161             aShapePtr = aSelectAttr->contextFeature()->firstResult()->shape();
162           }
163           if (aShapePtr.get()) {
164             const TopoDS_Shape aTDShape = aShapePtr->impl<TopoDS_Shape>();
165             Handle(AIS_InteractiveObject) anIO = myWorkshop->selection()->getIO(thePrs);
166             aOwnersList.Append(new StdSelect_BRepOwner(aTDShape, anIO));
167           }
168         }
169         else {
170           ResultPtr aFirstRes = aFeature->firstResult();
171           if (aFirstRes.get()) {
172             ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aFirstRes);
173             if (aBody.get() && (aBody->numberOfSubs() > 0))
174               collectSubBodies(aBody, aOwnersList);
175             else {
176               GeomShapePtr aShapePtr = ModelAPI_Tools::shape(aFirstRes);
177               if (aShapePtr.get()) {
178                 TopoDS_Shape aTDShape = aShapePtr->impl<TopoDS_Shape>();
179                 AISObjectPtr aIOPtr = myWorkshop->findPresentation(aFirstRes);
180                 if (aIOPtr.get()) {
181                   Handle(AIS_InteractiveObject) anIO =
182                     aIOPtr->impl<Handle(AIS_InteractiveObject)>();
183                   aOwnersList.Append(new StdSelect_BRepOwner(aTDShape, anIO));
184                 }
185                 else
186                   aOwnersList.Append(new StdSelect_BRepOwner(aTDShape));
187               }
188             }
189           }
190         }
191       }
192     }
193   }
194   aValid = (aOwnersList.Size() > 0); // only results with a shape can be filtered
195
196   // checks the owner by the AIS context activated filters
197   if (aOwnersList.Size() > 0) {
198     // the widget validator filter should be active, but during check by preselection
199     // it is not yet activated, so we need to activate/deactivate it manually
200     bool isActivated = isFilterActivated();
201     if (!isActivated) {
202       QIntList aModuleSelectionFilters = myWorkshop->module()->selectionFilters();
203       SelectMgr_ListOfFilter aSelectionFilters;
204       selectionFilters(aModuleSelectionFilters, aSelectionFilters);
205       /// after validation, the selection filters should be restored
206       myWorkshop->selectionActivate()->activateSelectionFilters(aSelectionFilters);
207     }
208
209     Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
210     if (!aContext.IsNull()) {
211       const SelectMgr_ListOfFilter& aFilters = aContext->Filters();
212       SelectMgr_ListIteratorOfListOfFilter anIt(aFilters);
213       AIS_NListOfEntityOwner::Iterator aOIt;
214       for (; anIt.More() && aValid; anIt.Next()) {
215         Handle(SelectMgr_Filter) aFilter = anIt.Value();
216         for (aOIt.Init(aOwnersList); aOIt.More(); aOIt.Next()) {
217           aValid = aFilter->IsOk(aOIt.Value());
218           if (!aValid)
219             break;
220         }
221         if (!aValid)
222           break;
223       }
224     }
225     if (!isActivated) {
226       // reset filters set in activateSelectionFilters above
227       myWorkshop->selectionActivate()->updateSelectionFilters();
228       clearValidatedCash();
229     }
230   }
231
232   // removes created owner
233   if (aOwnersList.Size() > 0 && thePrs->owner().IsNull()) {
234     myPresentedObject = ObjectPtr();
235   }
236   if (!aValid) {
237     // Clear attribute if it still has selection
238     AttributePtr anAttr = attribute();
239     std::string aType = anAttr->attributeType();
240     if (aType == ModelAPI_AttributeSelection::typeId()) {
241       AttributeSelectionPtr aSelectAttr =
242         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(anAttr);
243       aSelectAttr->removeTemporaryValues();
244     }
245   }
246   return aValid;
247 }
248
249 //********************************************************************
250 AttributePtr ModuleBase_WidgetValidated::attribute() const
251 {
252   return myFeature->attribute(attributeID());
253 }
254
255 //********************************************************************
256 bool ModuleBase_WidgetValidated::isValidSelection(const ModuleBase_ViewerPrsPtr& theValue)
257 {
258   bool aValid = false;
259   if (getValidState(theValue, aValid)) {
260     return aValid;
261   }
262   aValid = isValidSelectionCustom(theValue);
263   if (aValid)
264     aValid = isValidSelectionForAttribute(theValue, attribute());
265
266   storeValidState(theValue, aValid);
267   return aValid;
268 }
269
270 //********************************************************************
271 bool ModuleBase_WidgetValidated::isValidSelectionForAttribute(
272                                             const ModuleBase_ViewerPrsPtr& theValue,
273                                             const AttributePtr& theAttribute)
274 {
275   bool aValid = false;
276
277   // stores the current values of the widget attribute
278   bool isFlushesActived, isAttributeSetInitializedBlocked, isAttributeSendUpdatedBlocked;
279
280   blockAttribute(theAttribute, true, isFlushesActived, isAttributeSetInitializedBlocked,
281                  isAttributeSendUpdatedBlocked);
282
283   storeAttributeValue(theAttribute);
284
285   // saves the owner value to the widget attribute
286   aValid = setSelectionCustom(theValue);
287   if (aValid)
288     // checks the attribute validity
289     aValid = isValidAttribute(theAttribute);
290
291   // restores the current values of the widget attribute
292   restoreAttributeValue(theAttribute, aValid);
293
294   blockAttribute(theAttribute, false, isFlushesActived, isAttributeSetInitializedBlocked,
295                  isAttributeSendUpdatedBlocked);
296   /// NDS: The following rows are commented for issue #1452 (to be removed after debug)
297   /// This is not correct to perform it here because it might cause update selection and
298   /// the selection mechanizm will be circled: use the scenario of the bug with preselected point.
299   // In particular case the results are deleted and called as redisplayed inside of this
300   // highlight-selection, to they must be flushed as soon as possible.
301   // Example: selection of group-vertices subshapes with shift pressend on body. Without
302   //  these 4 lines below the application crashes because of left presentations on
303   //  removed results still in the viewer.
304   /*static Events_ID aDeletedEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
305   static Events_ID aRedispEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
306   Events_Loop::loop()->flush(aDeletedEvent);
307   Events_Loop::loop()->flush(aRedispEvent);
308   */
309   return aValid;
310 }
311
312 //********************************************************************
313 bool ModuleBase_WidgetValidated::isValidSelectionCustom(const ModuleBase_ViewerPrsPtr& thePrs)
314 {
315   return true;
316 }
317
318 //********************************************************************
319 bool ModuleBase_WidgetValidated::isValidAttribute(const AttributePtr& theAttribute)
320 {
321   SessionPtr aMgr = ModelAPI_Session::get();
322   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
323   std::string aValidatorID;
324   Events_InfoMessage anError;
325   return aFactory->validate(theAttribute, aValidatorID, anError);
326 }
327
328 //********************************************************************
329 bool ModuleBase_WidgetValidated::isFilterActivated() const
330 {
331   Handle(SelectMgr_Filter) aSelFilter = myWorkshop->validatorFilter();
332   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
333
334   return aViewer->hasSelectionFilter(aSelFilter);
335 }
336
337 //********************************************************************
338 void ModuleBase_WidgetValidated::selectionFilters(QIntList& theModuleSelectionFilters,
339                                                   SelectMgr_ListOfFilter& theSelectionFilters)
340 {
341   theSelectionFilters.Append(myWorkshop->validatorFilter());
342 }
343
344 //********************************************************************
345 void ModuleBase_WidgetValidated::blockAttribute(const AttributePtr& theAttribute,
346                                                 const bool& theToBlock,
347                                                 bool& isFlushesActived,
348                                                 bool& isAttributeSetInitializedBlocked,
349                                                 bool& isAttributeSendUpdatedBlocked)
350 {
351   blockFeatureAttribute(theAttribute, myFeature, theToBlock, isFlushesActived,
352                         isAttributeSetInitializedBlocked, isAttributeSendUpdatedBlocked);
353 }
354
355 //********************************************************************
356 void ModuleBase_WidgetValidated::blockFeatureAttribute(const AttributePtr& theAttribute,
357                                                 const FeaturePtr& theFeature,
358                                                 const bool& theToBlock,
359                                                 bool& isFlushesActived,
360                                                 bool& isAttributeSetInitializedBlocked,
361                                                 bool& isAttributeSendUpdatedBlocked)
362 {
363   Events_Loop* aLoop = Events_Loop::loop();
364   DataPtr aData = theFeature->data();
365   if (theToBlock) {
366     // blocks the flush signals to avoid the temporary objects visualization in the viewer
367     // they should not be shown in order to do not lose highlight by erasing them
368     isFlushesActived = aLoop->activateFlushes(false);
369
370     isAttributeSendUpdatedBlocked = aData->blockSendAttributeUpdated(true);
371     isAttributeSetInitializedBlocked = theAttribute->blockSetInitialized(true);
372   }
373   else {
374     aData->blockSendAttributeUpdated(isAttributeSendUpdatedBlocked, false);
375     theAttribute->blockSetInitialized(isAttributeSetInitializedBlocked);
376     aLoop->activateFlushes(isFlushesActived);
377   }
378 }
379
380 //********************************************************************
381 void ModuleBase_WidgetValidated::storeValidState(const ModuleBase_ViewerPrsPtr& theValue,
382                                                  const bool theValid)
383 {
384   GeomShapePtr aShape = theValue.get() ? theValue->shape() : GeomShapePtr();
385   if (aShape.get()) {
386     if (theValid) {
387       const TopoDS_Shape& aTDShape = aShape->impl<TopoDS_Shape>();
388       bool aValidPrsContains = myValidPrs.IsBound(aTDShape) &&
389                                theValue.get()->isEqual(myValidPrs.Find(aTDShape).get());
390       if (!aValidPrsContains) {
391   #ifdef LIST_OF_VALID_PRS
392         myValidPrs.append(theValue);
393   #else
394         myValidPrs.Bind(aTDShape, theValue);
395   #endif
396       // the commented code will be useful when the valid state of the presentation
397       // will be changable between activate/deactivate. Currently it does not happen.
398       //if (anInvalidPrs)
399       //  myInvalidPrs.removeOne(theValue);
400       }
401     }
402     else { // !theValid
403       if (aShape.get()) {
404         const TopoDS_Shape& aTDShape = aShape->impl<TopoDS_Shape>();
405         bool anIValidPrsContains = myInvalidPrs.IsBound(aTDShape) &&
406                                    theValue.get()->isEqual(myInvalidPrs.Find(aTDShape).get());
407         if (!anIValidPrsContains) {
408     #ifdef LIST_OF_VALID_PRS
409           myInvalidPrs.append(theValue);
410     #else
411           myInvalidPrs.Bind(aTDShape, theValue);
412     #endif
413         //if (!aValidPrs)
414         //  myValidPrs.removeOne(theValue);
415         }
416       }
417     }
418   }
419   #ifdef DEBUG_VALID_STATE
420     qDebug(QString("storeValidState: myValidPrs.size() = %1, myInvalidPrs.size() = %2")
421                    .arg(myValidPrs.count())
422                    .arg(myInvalidPrs.count()).toStdString().c_str());
423   #endif
424 }
425
426 //********************************************************************
427 bool ModuleBase_WidgetValidated::getValidState(const ModuleBase_ViewerPrsPtr& theValue,
428                                                bool& theValid)
429 {
430   if (!theValue.get())
431     return false;
432
433 #ifdef LIST_OF_VALID_PRS
434   bool aValidPrsContains = myValidPrs.contains(theValue);
435   bool anInvalidPrsContains = myInvalidPrs.contains(theValue);
436 #else
437   GeomShapePtr aShape = theValue.get() ? theValue->shape() : GeomShapePtr();
438   if (!aShape.get())
439     return false;
440
441   const TopoDS_Shape& aTDShape = aShape->impl<TopoDS_Shape>();
442   bool aValidPrsContains = myValidPrs.IsBound(aTDShape) &&
443                            theValue.get()->isEqual(myValidPrs.Find(aTDShape).get());
444
445   bool anInvalidPrsContains = myInvalidPrs.IsBound(aTDShape) &&
446                               theValue.get()->isEqual(myInvalidPrs.Find(aTDShape).get());
447   /*
448   bool aValidPrsContains = false, anInvalidPrsContains = false;
449   GeomShapePtr aShape = theValue.get() ? theValue->shape() : GeomShapePtr();
450   if (aShape.get()) {
451     aValidPrsContains = myValidPrs.contains(aShape);
452     anInvalidPrsContains = myInvalidPrs.contains(aShape);
453
454     if (aValidPrsContains)
455       aValidPrsContains = theValue == myValidPrs[aShape];
456     else
457       anInvalidPrsContains = theValue == myInvalidPrs[aShape];*/
458 #endif
459
460   if (aValidPrsContains)
461     theValid = true;
462   else if (anInvalidPrsContains)
463     theValid = false;
464
465   return aValidPrsContains || anInvalidPrsContains;
466 }
467
468 //********************************************************************
469 QList<ModuleBase_ViewerPrsPtr> ModuleBase_WidgetValidated::getFilteredSelected()
470 {
471   QList<ModuleBase_ViewerPrsPtr> aSelected = myWorkshop->selection()->getSelected(
472                                                        ModuleBase_ISelection::Viewer);
473
474   QList<ModuleBase_ViewerPrsPtr> anOBSelected = myWorkshop->selection()->getSelected(
475                                                        ModuleBase_ISelection::Browser);
476   // filter the OB presentations
477   filterPresentations(anOBSelected);
478   if (!anOBSelected.isEmpty())
479     ModuleBase_ISelection::appendSelected(anOBSelected, aSelected);
480
481   filterCompSolids(aSelected);
482
483   return aSelected;
484 }
485
486 //********************************************************************
487 void ModuleBase_WidgetValidated::filterPresentations(QList<ModuleBase_ViewerPrsPtr>& theValues)
488 {
489   QList<ModuleBase_ViewerPrsPtr> aValidatedValues;
490   foreach(ModuleBase_ViewerPrsPtr aPrs, theValues) {
491     if (isValidInFilters(aPrs))
492       aValidatedValues.append(aPrs);
493   }
494   if (aValidatedValues.size() != theValues.size()) {
495     theValues.clear();
496     theValues = aValidatedValues;
497   }
498 }
499
500 //********************************************************************
501 void ModuleBase_WidgetValidated::filterCompSolids(QList<ModuleBase_ViewerPrsPtr>& theValues)
502 {
503   std::set<ResultPtr> aFilterOut; // all objects that must be filtered out with their children
504   QList<ModuleBase_ViewerPrsPtr> aValidatedValues;
505
506   // Collect compsolids.
507   QList<ModuleBase_ViewerPrsPtr>::const_iterator anIt = theValues.begin(), aLast = theValues.end();
508   for(; anIt != aLast; anIt++) {
509     const ModuleBase_ViewerPrsPtr& aViewerPrs = *anIt;
510     ObjectPtr anObject = aViewerPrs->object();
511     ResultBodyPtr aResultCompSolid =
512       std::dynamic_pointer_cast<ModelAPI_ResultBody>(anObject);
513     if (aResultCompSolid.get()) {
514       for(int aSubIndex = 0; aSubIndex < aResultCompSolid->numberOfSubs(); aSubIndex++)
515         aFilterOut.insert(aResultCompSolid->subResult(aSubIndex));
516     } else { // it could be a whole feature selected, so, add all results of this feature
517       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
518       if (aFeature.get()) {
519         std::list<ResultPtr>::const_iterator aRes = aFeature->results().cbegin();
520         for(; aRes != aFeature->results().cend(); aRes++)
521           aFilterOut.insert(*aRes);
522       }
523     }
524   }
525
526   // Filter sub-solids of compsolids.
527   anIt = theValues.begin();
528   for(; anIt != aLast; anIt++) {
529     const ModuleBase_ViewerPrsPtr& aViewerPrs = *anIt;
530     ObjectPtr anObject = aViewerPrs->object();
531     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
532     while(aResult.get()) {
533       if (aFilterOut.find(aResult) != aFilterOut.end()) // skip if parent is filtered out
534         break;
535       aResult = ModelAPI_Tools::bodyOwner(aResult); // iterate all parents
536     }
537     if (aResult.get()) {
538       continue; // skip
539     } else {
540       aValidatedValues.append(*anIt);
541     }
542   }
543
544   if (aValidatedValues.size() != theValues.size()) {
545     theValues.clear();
546     theValues = aValidatedValues;
547   }
548 }