Salome HOME
f2583322883824d88e5af9f4b8f1841fec1ef0c5
[modules/shaper.git] / src / ModuleBase / ModuleBase_WidgetValidated.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 <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 aShape = aSelectAttr->value();
159           if (!aShape.get() && aSelectAttr->contextFeature().get() &&
160             aSelectAttr->contextFeature()->firstResult().get()) {
161             aShape = aSelectAttr->contextFeature()->firstResult()->shape();
162           }
163           if (aShape.get()) {
164             const TopoDS_Shape aTDShape = aShape->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 aResult = aFeature->firstResult();
171           if (aResult.get()) {
172             ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResult);
173             if (aBody.get() && (aBody->numberOfSubs() > 0))
174               collectSubBodies(aBody, aOwnersList);
175             else {
176               GeomShapePtr aShapePtr = ModelAPI_Tools::shape(aResult);
177               if (aShapePtr.get()) {
178                 TopoDS_Shape aTDShape = aShapePtr->impl<TopoDS_Shape>();
179                 AISObjectPtr aIOPtr = myWorkshop->findPresentation(aResult);
180                 if (aIOPtr.get()) {
181                   Handle(AIS_InteractiveObject) anIO = aIOPtr->impl<Handle(AIS_InteractiveObject)>();
182                   aOwnersList.Append(new StdSelect_BRepOwner(aTDShape, anIO));
183                 }
184                 else
185                   aOwnersList.Append(new StdSelect_BRepOwner(aTDShape));
186               }
187             }
188           }
189         }
190       }
191     }
192   }
193   aValid = (aOwnersList.Size() > 0); // only results with a shape can be filtered
194
195   // checks the owner by the AIS context activated filters
196   if (aOwnersList.Size() > 0) {
197     // the widget validator filter should be active, but during check by preselection
198     // it is not yet activated, so we need to activate/deactivate it manually
199     bool isActivated = isFilterActivated();
200     if (!isActivated) {
201       QIntList aModuleSelectionFilters = myWorkshop->module()->selectionFilters();
202       SelectMgr_ListOfFilter aSelectionFilters;
203       selectionFilters(aModuleSelectionFilters, aSelectionFilters);
204       /// after validation, the selection filters should be restored
205       myWorkshop->selectionActivate()->activateSelectionFilters(aSelectionFilters);
206     }
207
208     Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
209     if (!aContext.IsNull()) {
210       const SelectMgr_ListOfFilter& aFilters = aContext->Filters();
211       SelectMgr_ListIteratorOfListOfFilter anIt(aFilters);
212       AIS_NListOfEntityOwner::Iterator aOIt;
213       for (; anIt.More() && aValid; anIt.Next()) {
214         Handle(SelectMgr_Filter) aFilter = anIt.Value();
215         for (aOIt.Init(aOwnersList); aOIt.More(); aOIt.Next()) {
216           aValid = aFilter->IsOk(aOIt.Value());
217           if (!aValid)
218             break;
219         }
220         if (!aValid)
221           break;
222       }
223     }
224     if (!isActivated) {
225       // reset filters set in activateSelectionFilters above
226       myWorkshop->selectionActivate()->updateSelectionFilters();
227       clearValidatedCash();
228     }
229   }
230
231   // removes created owner
232   if (aOwnersList.Size() > 0 && thePrs->owner().IsNull()) {
233     myPresentedObject = ObjectPtr();
234   }
235   if (!aValid) {
236     // Clear attribute if it still has selection
237     AttributePtr anAttr = attribute();
238     std::string aType = anAttr->attributeType();
239     if (aType == ModelAPI_AttributeSelection::typeId()) {
240       AttributeSelectionPtr aSelectAttr =
241         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(anAttr);
242       aSelectAttr->removeTemporaryValues();
243     }
244   }
245   return aValid;
246 }
247
248 //********************************************************************
249 AttributePtr ModuleBase_WidgetValidated::attribute() const
250 {
251   return myFeature->attribute(attributeID());
252 }
253
254 //********************************************************************
255 bool ModuleBase_WidgetValidated::isValidSelection(const ModuleBase_ViewerPrsPtr& theValue)
256 {
257   bool aValid = false;
258   if (getValidState(theValue, aValid)) {
259     return aValid;
260   }
261   aValid = isValidSelectionCustom(theValue);
262   if (aValid)
263     aValid = isValidSelectionForAttribute(theValue, attribute());
264
265   storeValidState(theValue, aValid);
266   return aValid;
267 }
268
269 //********************************************************************
270 bool ModuleBase_WidgetValidated::isValidSelectionForAttribute(
271                                             const ModuleBase_ViewerPrsPtr& theValue,
272                                             const AttributePtr& theAttribute)
273 {
274   bool aValid = false;
275
276   // stores the current values of the widget attribute
277   bool isFlushesActived, isAttributeSetInitializedBlocked, isAttributeSendUpdatedBlocked;
278
279   blockAttribute(theAttribute, true, isFlushesActived, isAttributeSetInitializedBlocked,
280                  isAttributeSendUpdatedBlocked);
281
282   storeAttributeValue(theAttribute);
283
284   // saves the owner value to the widget attribute
285   aValid = setSelectionCustom(theValue);
286   if (aValid)
287     // checks the attribute validity
288     aValid = isValidAttribute(theAttribute);
289
290   // restores the current values of the widget attribute
291   restoreAttributeValue(theAttribute, aValid);
292
293   blockAttribute(theAttribute, false, isFlushesActived, isAttributeSetInitializedBlocked,
294                  isAttributeSendUpdatedBlocked);
295   /// NDS: The following rows are commented for issue #1452 (to be removed after debug)
296   /// This is not correct to perform it here because it might cause update selection and
297   /// the selection mechanizm will be circled: use the scenario of the bug with preselected point.
298   // In particular case the results are deleted and called as redisplayed inside of this
299   // highlight-selection, to they must be flushed as soon as possible.
300   // Example: selection of group-vertices subshapes with shift pressend on body. Without
301   //  these 4 lines below the application crashes because of left presentations on
302   //  removed results still in the viewer.
303   /*static Events_ID aDeletedEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
304   static Events_ID aRedispEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
305   Events_Loop::loop()->flush(aDeletedEvent);
306   Events_Loop::loop()->flush(aRedispEvent);
307   */
308   return aValid;
309 }
310
311 //********************************************************************
312 bool ModuleBase_WidgetValidated::isValidSelectionCustom(const ModuleBase_ViewerPrsPtr& thePrs)
313 {
314   return true;
315 }
316
317 //********************************************************************
318 bool ModuleBase_WidgetValidated::isValidAttribute(const AttributePtr& theAttribute)
319 {
320   SessionPtr aMgr = ModelAPI_Session::get();
321   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
322   std::string aValidatorID;
323   Events_InfoMessage anError;
324   return aFactory->validate(theAttribute, aValidatorID, anError);
325 }
326
327 //********************************************************************
328 bool ModuleBase_WidgetValidated::isFilterActivated() const
329 {
330   bool isActivated = false;
331
332   Handle(SelectMgr_Filter) aSelFilter = myWorkshop->validatorFilter();
333   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
334
335   return aViewer->hasSelectionFilter(aSelFilter);
336 }
337
338 //********************************************************************
339 void ModuleBase_WidgetValidated::selectionFilters(QIntList& theModuleSelectionFilters,
340                                                   SelectMgr_ListOfFilter& theSelectionFilters)
341 {
342   theSelectionFilters.Append(myWorkshop->validatorFilter());
343 }
344
345 //********************************************************************
346 void ModuleBase_WidgetValidated::blockAttribute(const AttributePtr& theAttribute,
347                                                 const bool& theToBlock,
348                                                 bool& isFlushesActived,
349                                                 bool& isAttributeSetInitializedBlocked,
350                                                 bool& isAttributeSendUpdatedBlocked)
351 {
352   blockFeatureAttribute(theAttribute, myFeature, theToBlock, isFlushesActived,
353                         isAttributeSetInitializedBlocked, isAttributeSendUpdatedBlocked);
354 }
355
356 //********************************************************************
357 void ModuleBase_WidgetValidated::blockFeatureAttribute(const AttributePtr& theAttribute,
358                                                 const FeaturePtr& theFeature,
359                                                 const bool& theToBlock,
360                                                 bool& isFlushesActived,
361                                                 bool& isAttributeSetInitializedBlocked,
362                                                 bool& isAttributeSendUpdatedBlocked)
363 {
364   Events_Loop* aLoop = Events_Loop::loop();
365   DataPtr aData = theFeature->data();
366   if (theToBlock) {
367     // blocks the flush signals to avoid the temporary objects visualization in the viewer
368     // they should not be shown in order to do not lose highlight by erasing them
369     isFlushesActived = aLoop->activateFlushes(false);
370
371     isAttributeSendUpdatedBlocked = aData->blockSendAttributeUpdated(true);
372     isAttributeSetInitializedBlocked = theAttribute->blockSetInitialized(true);
373   }
374   else {
375     aData->blockSendAttributeUpdated(isAttributeSendUpdatedBlocked, false);
376     theAttribute->blockSetInitialized(isAttributeSetInitializedBlocked);
377     aLoop->activateFlushes(isFlushesActived);
378   }
379 }
380
381 //********************************************************************
382 void ModuleBase_WidgetValidated::storeValidState(const ModuleBase_ViewerPrsPtr& theValue,
383                                                  const bool theValid)
384 {
385   GeomShapePtr aShape = theValue.get() ? theValue->shape() : GeomShapePtr();
386   if (aShape.get()) {
387     if (theValid) {
388       const TopoDS_Shape& aTDShape = aShape->impl<TopoDS_Shape>();
389       bool aValidPrsContains = myValidPrs.IsBound(aTDShape) &&
390                                theValue.get()->isEqual(myValidPrs.Find(aTDShape).get());
391       if (!aValidPrsContains) {
392   #ifdef LIST_OF_VALID_PRS
393         myValidPrs.append(theValue);
394   #else
395         myValidPrs.Bind(aTDShape, theValue);
396   #endif
397       // the commented code will be useful when the valid state of the presentation
398       // will be changable between activate/deactivate. Currently it does not happen.
399       //if (anInvalidPrs)
400       //  myInvalidPrs.removeOne(theValue);
401       }
402     }
403     else { // !theValid
404       if (aShape.get()) {
405         const TopoDS_Shape& aTDShape = aShape->impl<TopoDS_Shape>();
406         bool anIValidPrsContains = myInvalidPrs.IsBound(aTDShape) &&
407                                    theValue.get()->isEqual(myInvalidPrs.Find(aTDShape).get());
408         if (!anIValidPrsContains) {
409     #ifdef LIST_OF_VALID_PRS
410           myInvalidPrs.append(theValue);
411     #else
412           myInvalidPrs.Bind(aTDShape, theValue);
413     #endif
414         //if (!aValidPrs)
415         //  myValidPrs.removeOne(theValue);
416         }
417       }
418     }
419   }
420   #ifdef DEBUG_VALID_STATE
421     qDebug(QString("storeValidState: myValidPrs.size() = %1, myInvalidPrs.size() = %2")
422                    .arg(myValidPrs.count())
423                    .arg(myInvalidPrs.count()).toStdString().c_str());
424   #endif
425 }
426
427 //********************************************************************
428 bool ModuleBase_WidgetValidated::getValidState(const ModuleBase_ViewerPrsPtr& theValue,
429                                                bool& theValid)
430 {
431   if (!theValue.get())
432     return false;
433
434 #ifdef LIST_OF_VALID_PRS
435   bool aValidPrsContains = myValidPrs.contains(theValue);
436   bool anInvalidPrsContains = myInvalidPrs.contains(theValue);
437 #else
438   GeomShapePtr aShape = theValue.get() ? theValue->shape() : GeomShapePtr();
439   if (!aShape.get())
440     return false;
441
442   const TopoDS_Shape& aTDShape = aShape->impl<TopoDS_Shape>();
443   bool aValidPrsContains = myValidPrs.IsBound(aTDShape) &&
444                            theValue.get()->isEqual(myValidPrs.Find(aTDShape).get());
445
446   bool anInvalidPrsContains = myInvalidPrs.IsBound(aTDShape) &&
447                               theValue.get()->isEqual(myInvalidPrs.Find(aTDShape).get());
448   /*
449   bool aValidPrsContains = false, anInvalidPrsContains = false;
450   GeomShapePtr aShape = theValue.get() ? theValue->shape() : GeomShapePtr();
451   if (aShape.get()) {
452     aValidPrsContains = myValidPrs.contains(aShape);
453     anInvalidPrsContains = myInvalidPrs.contains(aShape);
454
455     if (aValidPrsContains)
456       aValidPrsContains = theValue == myValidPrs[aShape];
457     else
458       anInvalidPrsContains = theValue == myInvalidPrs[aShape];*/
459 #endif
460
461   if (aValidPrsContains)
462     theValid = true;
463   else if (anInvalidPrsContains)
464     theValid = false;
465
466   return aValidPrsContains || anInvalidPrsContains;
467 }
468
469 //********************************************************************
470 QList<ModuleBase_ViewerPrsPtr> ModuleBase_WidgetValidated::getFilteredSelected()
471 {
472   QList<ModuleBase_ViewerPrsPtr> aSelected = myWorkshop->selection()->getSelected(
473                                                        ModuleBase_ISelection::Viewer);
474
475   QList<ModuleBase_ViewerPrsPtr> anOBSelected = myWorkshop->selection()->getSelected(
476                                                        ModuleBase_ISelection::Browser);
477   // filter the OB presentations
478   filterPresentations(anOBSelected);
479   if (!anOBSelected.isEmpty())
480     ModuleBase_ISelection::appendSelected(anOBSelected, aSelected);
481
482   filterCompSolids(aSelected);
483
484   return aSelected;
485 }
486
487 //********************************************************************
488 void ModuleBase_WidgetValidated::filterPresentations(QList<ModuleBase_ViewerPrsPtr>& theValues)
489 {
490   QList<ModuleBase_ViewerPrsPtr> aValidatedValues;
491   foreach(ModuleBase_ViewerPrsPtr aPrs, theValues) {
492     if (isValidInFilters(aPrs))
493       aValidatedValues.append(aPrs);
494   }
495   if (aValidatedValues.size() != theValues.size()) {
496     theValues.clear();
497     theValues = aValidatedValues;
498   }
499 }
500
501 //********************************************************************
502 void ModuleBase_WidgetValidated::filterCompSolids(QList<ModuleBase_ViewerPrsPtr>& theValues)
503 {
504   std::set<ResultPtr> aFilterOut; // all objects that must be filtered out with their children
505   QList<ModuleBase_ViewerPrsPtr> aValidatedValues;
506
507   // Collect compsolids.
508   QList<ModuleBase_ViewerPrsPtr>::const_iterator anIt = theValues.begin(), aLast = theValues.end();
509   for(; anIt != aLast; anIt++) {
510     const ModuleBase_ViewerPrsPtr& aViewerPrs = *anIt;
511     ObjectPtr anObject = aViewerPrs->object();
512     ResultBodyPtr aResultCompSolid =
513       std::dynamic_pointer_cast<ModelAPI_ResultBody>(anObject);
514     if (aResultCompSolid.get()) {
515       for(int aSubIndex = 0; aSubIndex < aResultCompSolid->numberOfSubs(); aSubIndex++)
516         aFilterOut.insert(aResultCompSolid->subResult(aSubIndex));
517     } else { // it could be a whole feature selected, so, add all results of this feature
518       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
519       if (aFeature.get()) {
520         std::list<ResultPtr>::const_iterator aRes = aFeature->results().cbegin();
521         for(; aRes != aFeature->results().cend(); aRes++)
522           aFilterOut.insert(*aRes);
523       }
524     }
525   }
526
527   // Filter sub-solids of compsolids.
528   anIt = theValues.begin();
529   for(; anIt != aLast; anIt++) {
530     const ModuleBase_ViewerPrsPtr& aViewerPrs = *anIt;
531     ObjectPtr anObject = aViewerPrs->object();
532     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
533     while(aResult.get()) {
534       if (aFilterOut.find(aResult) != aFilterOut.end()) // skip if parent is filtered out
535         break;
536       aResult = ModelAPI_Tools::bodyOwner(aResult); // iterate all parents
537     }
538     if (aResult.get()) {
539       continue; // skip
540     } else {
541       aValidatedValues.append(*anIt);
542     }
543   }
544
545   if (aValidatedValues.size() != theValues.size()) {
546     theValues.clear();
547     theValues = aValidatedValues;
548   }
549 }