Salome HOME
1536c3066d273a678bbfeaf32187cff23e7a088b
[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 =
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   bool isActivated = false;
332
333   Handle(SelectMgr_Filter) aSelFilter = myWorkshop->validatorFilter();
334   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
335
336   return aViewer->hasSelectionFilter(aSelFilter);
337 }
338
339 //********************************************************************
340 void ModuleBase_WidgetValidated::selectionFilters(QIntList& theModuleSelectionFilters,
341                                                   SelectMgr_ListOfFilter& theSelectionFilters)
342 {
343   theSelectionFilters.Append(myWorkshop->validatorFilter());
344 }
345
346 //********************************************************************
347 void ModuleBase_WidgetValidated::blockAttribute(const AttributePtr& theAttribute,
348                                                 const bool& theToBlock,
349                                                 bool& isFlushesActived,
350                                                 bool& isAttributeSetInitializedBlocked,
351                                                 bool& isAttributeSendUpdatedBlocked)
352 {
353   blockFeatureAttribute(theAttribute, myFeature, theToBlock, isFlushesActived,
354                         isAttributeSetInitializedBlocked, isAttributeSendUpdatedBlocked);
355 }
356
357 //********************************************************************
358 void ModuleBase_WidgetValidated::blockFeatureAttribute(const AttributePtr& theAttribute,
359                                                 const FeaturePtr& theFeature,
360                                                 const bool& theToBlock,
361                                                 bool& isFlushesActived,
362                                                 bool& isAttributeSetInitializedBlocked,
363                                                 bool& isAttributeSendUpdatedBlocked)
364 {
365   Events_Loop* aLoop = Events_Loop::loop();
366   DataPtr aData = theFeature->data();
367   if (theToBlock) {
368     // blocks the flush signals to avoid the temporary objects visualization in the viewer
369     // they should not be shown in order to do not lose highlight by erasing them
370     isFlushesActived = aLoop->activateFlushes(false);
371
372     isAttributeSendUpdatedBlocked = aData->blockSendAttributeUpdated(true);
373     isAttributeSetInitializedBlocked = theAttribute->blockSetInitialized(true);
374   }
375   else {
376     aData->blockSendAttributeUpdated(isAttributeSendUpdatedBlocked, false);
377     theAttribute->blockSetInitialized(isAttributeSetInitializedBlocked);
378     aLoop->activateFlushes(isFlushesActived);
379   }
380 }
381
382 //********************************************************************
383 void ModuleBase_WidgetValidated::storeValidState(const ModuleBase_ViewerPrsPtr& theValue,
384                                                  const bool theValid)
385 {
386   GeomShapePtr aShape = theValue.get() ? theValue->shape() : GeomShapePtr();
387   if (aShape.get()) {
388     if (theValid) {
389       const TopoDS_Shape& aTDShape = aShape->impl<TopoDS_Shape>();
390       bool aValidPrsContains = myValidPrs.IsBound(aTDShape) &&
391                                theValue.get()->isEqual(myValidPrs.Find(aTDShape).get());
392       if (!aValidPrsContains) {
393   #ifdef LIST_OF_VALID_PRS
394         myValidPrs.append(theValue);
395   #else
396         myValidPrs.Bind(aTDShape, theValue);
397   #endif
398       // the commented code will be useful when the valid state of the presentation
399       // will be changable between activate/deactivate. Currently it does not happen.
400       //if (anInvalidPrs)
401       //  myInvalidPrs.removeOne(theValue);
402       }
403     }
404     else { // !theValid
405       if (aShape.get()) {
406         const TopoDS_Shape& aTDShape = aShape->impl<TopoDS_Shape>();
407         bool anIValidPrsContains = myInvalidPrs.IsBound(aTDShape) &&
408                                    theValue.get()->isEqual(myInvalidPrs.Find(aTDShape).get());
409         if (!anIValidPrsContains) {
410     #ifdef LIST_OF_VALID_PRS
411           myInvalidPrs.append(theValue);
412     #else
413           myInvalidPrs.Bind(aTDShape, theValue);
414     #endif
415         //if (!aValidPrs)
416         //  myValidPrs.removeOne(theValue);
417         }
418       }
419     }
420   }
421   #ifdef DEBUG_VALID_STATE
422     qDebug(QString("storeValidState: myValidPrs.size() = %1, myInvalidPrs.size() = %2")
423                    .arg(myValidPrs.count())
424                    .arg(myInvalidPrs.count()).toStdString().c_str());
425   #endif
426 }
427
428 //********************************************************************
429 bool ModuleBase_WidgetValidated::getValidState(const ModuleBase_ViewerPrsPtr& theValue,
430                                                bool& theValid)
431 {
432   if (!theValue.get())
433     return false;
434
435 #ifdef LIST_OF_VALID_PRS
436   bool aValidPrsContains = myValidPrs.contains(theValue);
437   bool anInvalidPrsContains = myInvalidPrs.contains(theValue);
438 #else
439   GeomShapePtr aShape = theValue.get() ? theValue->shape() : GeomShapePtr();
440   if (!aShape.get())
441     return false;
442
443   const TopoDS_Shape& aTDShape = aShape->impl<TopoDS_Shape>();
444   bool aValidPrsContains = myValidPrs.IsBound(aTDShape) &&
445                            theValue.get()->isEqual(myValidPrs.Find(aTDShape).get());
446
447   bool anInvalidPrsContains = myInvalidPrs.IsBound(aTDShape) &&
448                               theValue.get()->isEqual(myInvalidPrs.Find(aTDShape).get());
449   /*
450   bool aValidPrsContains = false, anInvalidPrsContains = false;
451   GeomShapePtr aShape = theValue.get() ? theValue->shape() : GeomShapePtr();
452   if (aShape.get()) {
453     aValidPrsContains = myValidPrs.contains(aShape);
454     anInvalidPrsContains = myInvalidPrs.contains(aShape);
455
456     if (aValidPrsContains)
457       aValidPrsContains = theValue == myValidPrs[aShape];
458     else
459       anInvalidPrsContains = theValue == myInvalidPrs[aShape];*/
460 #endif
461
462   if (aValidPrsContains)
463     theValid = true;
464   else if (anInvalidPrsContains)
465     theValid = false;
466
467   return aValidPrsContains || anInvalidPrsContains;
468 }
469
470 //********************************************************************
471 QList<ModuleBase_ViewerPrsPtr> ModuleBase_WidgetValidated::getFilteredSelected()
472 {
473   QList<ModuleBase_ViewerPrsPtr> aSelected = myWorkshop->selection()->getSelected(
474                                                        ModuleBase_ISelection::Viewer);
475
476   QList<ModuleBase_ViewerPrsPtr> anOBSelected = myWorkshop->selection()->getSelected(
477                                                        ModuleBase_ISelection::Browser);
478   // filter the OB presentations
479   filterPresentations(anOBSelected);
480   if (!anOBSelected.isEmpty())
481     ModuleBase_ISelection::appendSelected(anOBSelected, aSelected);
482
483   filterCompSolids(aSelected);
484
485   return aSelected;
486 }
487
488 //********************************************************************
489 void ModuleBase_WidgetValidated::filterPresentations(QList<ModuleBase_ViewerPrsPtr>& theValues)
490 {
491   QList<ModuleBase_ViewerPrsPtr> aValidatedValues;
492   foreach(ModuleBase_ViewerPrsPtr aPrs, theValues) {
493     if (isValidInFilters(aPrs))
494       aValidatedValues.append(aPrs);
495   }
496   if (aValidatedValues.size() != theValues.size()) {
497     theValues.clear();
498     theValues = aValidatedValues;
499   }
500 }
501
502 //********************************************************************
503 void ModuleBase_WidgetValidated::filterCompSolids(QList<ModuleBase_ViewerPrsPtr>& theValues)
504 {
505   std::set<ResultPtr> aFilterOut; // all objects that must be filtered out with their children
506   QList<ModuleBase_ViewerPrsPtr> aValidatedValues;
507
508   // Collect compsolids.
509   QList<ModuleBase_ViewerPrsPtr>::const_iterator anIt = theValues.begin(), aLast = theValues.end();
510   for(; anIt != aLast; anIt++) {
511     const ModuleBase_ViewerPrsPtr& aViewerPrs = *anIt;
512     ObjectPtr anObject = aViewerPrs->object();
513     ResultBodyPtr aResultCompSolid =
514       std::dynamic_pointer_cast<ModelAPI_ResultBody>(anObject);
515     if (aResultCompSolid.get()) {
516       for(int aSubIndex = 0; aSubIndex < aResultCompSolid->numberOfSubs(); aSubIndex++)
517         aFilterOut.insert(aResultCompSolid->subResult(aSubIndex));
518     } else { // it could be a whole feature selected, so, add all results of this feature
519       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
520       if (aFeature.get()) {
521         std::list<ResultPtr>::const_iterator aRes = aFeature->results().cbegin();
522         for(; aRes != aFeature->results().cend(); aRes++)
523           aFilterOut.insert(*aRes);
524       }
525     }
526   }
527
528   // Filter sub-solids of compsolids.
529   anIt = theValues.begin();
530   for(; anIt != aLast; anIt++) {
531     const ModuleBase_ViewerPrsPtr& aViewerPrs = *anIt;
532     ObjectPtr anObject = aViewerPrs->object();
533     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
534     while(aResult.get()) {
535       if (aFilterOut.find(aResult) != aFilterOut.end()) // skip if parent is filtered out
536         break;
537       aResult = ModelAPI_Tools::bodyOwner(aResult); // iterate all parents
538     }
539     if (aResult.get()) {
540       continue; // skip
541     } else {
542       aValidatedValues.append(*anIt);
543     }
544   }
545
546   if (aValidatedValues.size() != theValues.size()) {
547     theValues.clear();
548     theValues = aValidatedValues;
549   }
550 }