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