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