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