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