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