Salome HOME
Issue #390 Selection restore problems during edit operation
[modules/shaper.git] / src / ModuleBase / ModuleBase_WidgetShapeSelector.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        ModuleBase_WidgetShapeSelector.h
4 // Created:     2 June 2014
5 // Author:      Vitaly Smetannikov
6
7 #include <ModuleBase_WidgetShapeSelector.h>
8 #include <ModuleBase_Definitions.h>
9 #include <ModuleBase_ISelection.h>
10 #include <ModuleBase_IWorkshop.h>
11 #include <ModuleBase_IViewer.h>
12 #include <ModuleBase_Tools.h>
13 #include <ModuleBase_FilterFactory.h>
14 #include <ModuleBase_Filter.h>
15
16 #include <Config_WidgetAPI.h>
17 #include <Events_Loop.h>
18 #include <Events_Message.h>
19 #include <GeomAPI_Interface.h>
20 #include <GeomAPI_Shape.h>
21
22 #include <ModelAPI_AttributeReference.h>
23 #include <ModelAPI_Data.h>
24 #include <ModelAPI_Document.h>
25 #include <ModelAPI_Events.h>
26 #include <ModelAPI_Feature.h>
27 #include <ModelAPI_Result.h>
28 #include <ModelAPI_ResultConstruction.h>
29 #include <ModelAPI_AttributeReference.h>
30 #include <ModelAPI_AttributeSelection.h>
31 #include <ModelAPI_Session.h>
32 #include <ModelAPI_Tools.h>
33 #include <ModelAPI_ResultBody.h>
34 #include <ModelAPI_AttributeRefAttr.h>
35 #include <ModelAPI_Validator.h>
36 #include <ModelAPI_ResultValidator.h>
37 #include <ModelAPI_RefAttrValidator.h>
38 #include <ModelAPI_ShapeValidator.h>
39
40 #include <Config_WidgetAPI.h>
41 #include <Events_Error.h>
42
43 #include <GeomAPI_Shape.h>
44
45 #include <SelectMgr_ListIteratorOfListOfFilter.hxx>
46 #include <TopoDS_Shape.hxx>
47 #include <TopExp_Explorer.hxx>
48
49 #include <QWidget>
50 #include <QLayout>
51 #include <QLabel>
52 #include <QLineEdit>
53 #include <QToolButton>
54 #include <QString>
55 #include <QEvent>
56 #include <QDockWidget>
57 #include <QApplication>
58
59 #include <TopExp_Explorer.hxx>
60 #include <TopoDS_Shape.hxx>
61
62 #include <memory>
63
64 #include <list>
65 #include <string>
66
67 typedef QMap<QString, TopAbs_ShapeEnum> ShapeTypes;
68 static ShapeTypes MyShapeTypes;
69
70 TopAbs_ShapeEnum ModuleBase_WidgetShapeSelector::shapeType(const QString& theType)
71 {
72   if (MyShapeTypes.count() == 0) {
73     MyShapeTypes["face"] = TopAbs_FACE;
74     MyShapeTypes["faces"] = TopAbs_FACE;
75     MyShapeTypes["vertex"] = TopAbs_VERTEX;
76     MyShapeTypes["vertices"] = TopAbs_VERTEX;
77     MyShapeTypes["wire"] = TopAbs_WIRE;
78     MyShapeTypes["edge"] = TopAbs_EDGE;
79     MyShapeTypes["edges"] = TopAbs_EDGE;
80     MyShapeTypes["shell"] = TopAbs_SHELL;
81     MyShapeTypes["solid"] = TopAbs_SOLID;
82     MyShapeTypes["solids"] = TopAbs_SOLID;
83   }
84   QString aType = theType.toLower();
85   if (MyShapeTypes.contains(aType))
86     return MyShapeTypes[aType];
87   Events_Error::send("Shape type defined in XML is not implemented!");
88   return TopAbs_SHAPE;
89 }
90
91 ModuleBase_WidgetShapeSelector::ModuleBase_WidgetShapeSelector(QWidget* theParent,
92                                                      ModuleBase_IWorkshop* theWorkshop,
93                                                      const Config_WidgetAPI* theData,
94                                                      const std::string& theParentId)
95     : ModuleBase_ModelWidget(theParent, theData, theParentId),
96       myWorkshop(theWorkshop), myIsActive(false)
97 {
98   myContainer = new QWidget(theParent);
99   QHBoxLayout* aLayout = new QHBoxLayout(myContainer);
100   ModuleBase_Tools::adjustMargins(aLayout);
101
102   QString aLabelText = QString::fromStdString(theData->widgetLabel());
103   QString aLabelIcon = QString::fromStdString(theData->widgetIcon());
104   myLabel = new QLabel(aLabelText, myContainer);
105   if (!aLabelIcon.isEmpty())
106     myLabel->setPixmap(QPixmap(aLabelIcon));
107
108   aLayout->addWidget(myLabel);
109
110   QString aToolTip = QString::fromStdString(theData->widgetTooltip());
111   myTextLine = new QLineEdit(myContainer);
112   myTextLine->setReadOnly(true);
113   myTextLine->setToolTip(aToolTip);
114   myTextLine->installEventFilter(this);
115
116   aLayout->addWidget(myTextLine, 1);
117
118   std::string aTypes = theData->getProperty("shape_types");
119   myShapeTypes = QString(aTypes.c_str()).split(' ', QString::SkipEmptyParts);
120
121   std::string aObjTypes = theData->getProperty("object_types");
122   myObjectTypes = QString(aObjTypes.c_str()).split(' ', QString::SkipEmptyParts);
123 }
124
125 //********************************************************************
126 ModuleBase_WidgetShapeSelector::~ModuleBase_WidgetShapeSelector()
127 {
128   activateSelection(false);
129 }
130
131 //********************************************************************
132 bool ModuleBase_WidgetShapeSelector::storeValueCustom() const
133 {
134   FeaturePtr aSelectedFeature = ModelAPI_Feature::feature(mySelectedObject);
135   if (aSelectedFeature == myFeature)  // In order to avoid selection of the same object
136     return false;
137
138   DataPtr aData = myFeature->data();
139   AttributeReferencePtr aRef = aData->reference(attributeID());
140   if (aRef) {
141     ObjectPtr aObject = aRef->value();
142     if (!(aObject && aObject->isSame(mySelectedObject))) {
143       aRef->setValue(mySelectedObject);
144       updateObject(myFeature);
145       return true;
146     }
147   } else {
148     AttributeRefAttrPtr aRefAttr = aData->refattr(attributeID());
149     if (aRefAttr) {
150       ObjectPtr aObject = aRefAttr->object();
151       if (!(aObject && aObject->isSame(mySelectedObject))) {
152         aRefAttr->setObject(mySelectedObject);
153         updateObject(myFeature);
154         return true;
155       }
156     } else {
157       AttributeSelectionPtr aSelectAttr = aData->selection(attributeID());
158       ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(mySelectedObject);
159       if (aSelectAttr && aBody && (myShape.get() != NULL)) {
160         aSelectAttr->setValue(aBody, myShape);
161         updateObject(myFeature);
162         return true;
163       }
164     }
165   }
166   return false;
167 }
168
169 //********************************************************************
170 void ModuleBase_WidgetShapeSelector::clearAttribute()
171 {
172   DataPtr aData = myFeature->data();
173   AttributeSelectionPtr aSelect = aData->selection(attributeID());
174   if (aSelect) {
175     aSelect->setValue(ResultPtr(), std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape()));
176     return;
177   }
178   AttributeRefAttrPtr aRefAttr = aData->refattr(attributeID());
179   if (aRefAttr) {
180     aRefAttr->setObject(ObjectPtr());
181     return;
182   }
183   AttributeReferencePtr aRef = aData->reference(attributeID());
184   if (aRef) {
185     aRef->setObject(ObjectPtr());
186   }
187 }
188
189 //********************************************************************
190 bool ModuleBase_WidgetShapeSelector::restoreValue()
191 {
192   DataPtr aData = myFeature->data();
193   bool isBlocked = this->blockSignals(true);
194
195   AttributeSelectionPtr aSelect = aData->selection(attributeID());
196   if (aSelect) {
197     mySelectedObject = aSelect->context();
198     myShape = aSelect->value();
199   } else {
200     AttributeRefAttrPtr aRefAttr = aData->refattr(attributeID());
201     if (aRefAttr) {
202       mySelectedObject = aRefAttr->object();
203     } else {
204       AttributeReferencePtr aRef = aData->reference(attributeID());
205       if (aRef) {
206         mySelectedObject = aRef->value();
207       }
208     }
209   }
210   updateSelectionName();
211
212   this->blockSignals(isBlocked);
213   return true;
214 }
215
216 //********************************************************************
217 QList<QWidget*> ModuleBase_WidgetShapeSelector::getControls() const
218 {
219   QList<QWidget*> aControls;
220   aControls.append(myTextLine);
221   return aControls;
222 }
223
224 //********************************************************************
225 void ModuleBase_WidgetShapeSelector::onSelectionChanged()
226 {
227   // In order to make reselection possible
228   // TODO: check with MPV clearAttribute();
229
230   //QObjectPtrList aObjects = myWorkshop->selection()->selectedPresentations();
231   QList<ModuleBase_ViewerPrs> aSelected = myWorkshop->selection()->getSelected();
232   if (aSelected.size() > 0) {
233     if (setSelection(aSelected.first()))
234       emit focusOutWidget(this);
235   }
236 }
237
238 //********************************************************************
239 bool ModuleBase_WidgetShapeSelector::setSelection(ModuleBase_ViewerPrs theValue)
240 {
241   ObjectPtr aObject = theValue.object();
242   if ((!mySelectedObject) && (!aObject))
243     return false;
244
245   // Check that the selected object is result (others can not be accepted)
246   ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObject);
247   if (!aRes)
248     return false;
249
250   if (myFeature) {
251     // We can not select a result of our feature
252     const std::list<std::shared_ptr<ModelAPI_Result>>& aResList = myFeature->results();
253     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aIt;
254     for (aIt = aResList.cbegin(); aIt != aResList.cend(); ++aIt) {
255       if ((*aIt) == aRes)
256         return false;
257     }
258   }
259   // Check that object belongs to active document or PartSet
260   DocumentPtr aDoc = aRes->document();
261   SessionPtr aMgr = ModelAPI_Session::get();
262   if (!(aDoc == aMgr->activeDocument()) && !(aDoc == aMgr->moduleDocument()))
263     return false;
264
265   // Check that the result has a shape
266   GeomShapePtr aShape = ModelAPI_Tools::shape(aRes);
267   if (!aShape)
268     return false;
269
270   /// Check that object has acceptable type
271   if (!acceptObjectType(aObject)) 
272     return false;
273
274   // Get sub-shapes from local selection
275   if (!theValue.shape().IsNull()) {
276     aShape = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape());
277     aShape->setImpl(new TopoDS_Shape(theValue.shape()));
278   }
279
280   // Check that the selection corresponds to selection type
281   if (!acceptSubShape(aShape))
282     return false;
283 //  if (!acceptObjectShape(aObject))
284 //      return false;
285
286   // Check whether the value is valid for the viewer selection filters
287   Handle(SelectMgr_EntityOwner) anOwner = theValue.owner();
288   if (!anOwner.IsNull()) {
289     SelectMgr_ListOfFilter aFilters;
290     selectionFilters(aFilters);
291     SelectMgr_ListIteratorOfListOfFilter aIt(aFilters);
292     for (; aIt.More(); aIt.Next()) {
293       const Handle(SelectMgr_Filter)& aFilter = aIt.Value();
294       if (!aFilter->IsOk(anOwner))
295         return false;
296     }
297   }
298   if (isValid(aObject, aShape)) {
299     setObject(aObject, aShape);
300     return true;
301   }
302   return false;
303 }
304
305 //********************************************************************
306 void ModuleBase_WidgetShapeSelector::setObject(ObjectPtr theObj, std::shared_ptr<GeomAPI_Shape> theShape)
307 {
308   mySelectedObject = theObj;
309   myShape = theShape;
310   if (mySelectedObject) {
311     raisePanel();
312   } 
313   updateSelectionName();
314   emit valuesChanged();
315 }
316
317 //********************************************************************
318 //bool ModuleBase_WidgetShapeSelector::acceptObjectShape(const ObjectPtr theResult) const
319 //{
320 //  ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theResult);
321 //
322 //  // Check that the shape of necessary type
323 //  std::shared_ptr<GeomAPI_Shape> aShapePtr = ModelAPI_Tools::shape(aResult);
324 //  if (!aShapePtr)
325 //    return false;
326 //  TopoDS_Shape aShape = aShapePtr->impl<TopoDS_Shape>();
327 //  if (aShape.IsNull())
328 //    return false;
329 //
330 //  TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
331 //  if (aShapeType == TopAbs_COMPOUND) {
332 //    foreach (QString aType,
333 //      myShapeTypes) {
334 //      TopExp_Explorer aEx(aShape, shapeType(aType));
335 //      if (aEx.More())
336 //        return true;
337 //    }
338 //  } else {
339 //    foreach (QString aType, myShapeTypes) {
340 //      if (shapeType(aType) == aShapeType)
341 //        return true;
342 //    }
343 //  }
344 //  return false;
345 //}
346
347 //********************************************************************
348 bool ModuleBase_WidgetShapeSelector::acceptSubShape(std::shared_ptr<GeomAPI_Shape> theShape) const
349 {
350   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
351   foreach (QString aType, myShapeTypes) {
352     if (aShape.ShapeType() == shapeType(aType))
353       return true;
354   }
355   return false;
356 }
357
358 //********************************************************************
359 bool ModuleBase_WidgetShapeSelector::acceptObjectType(const ObjectPtr theObject) const
360 {
361   // Definition of types is not obligatory. If types are not defined then
362   // it means that accepted any type
363   if (myObjectTypes.isEmpty())
364     return true;
365
366   foreach (QString aType, myObjectTypes) {
367     if (aType.toLower() == "construction") {
368       ResultConstructionPtr aConstr = 
369         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theObject);
370       return (aConstr != NULL);
371     } // ToDo: Process other types of objects
372   }
373   // Object type is defined but not found
374   return false;
375 }
376
377
378 //********************************************************************
379 void ModuleBase_WidgetShapeSelector::updateSelectionName()
380 {
381   DataPtr aData = myFeature->data();
382   bool isNameUpdated = false;
383   if (aData.get() != NULL) {
384     AttributeSelectionPtr aSelect = aData->selection(attributeID());
385     if (aSelect) {
386       myTextLine->setText(QString::fromStdString(aSelect->namingName()));
387       isNameUpdated = true;
388     }
389   }
390   if (!isNameUpdated) {
391     if (mySelectedObject) {
392       std::string aName = mySelectedObject->data()->name();
393       myTextLine->setText(QString::fromStdString(aName));
394     } else {
395       if (myIsActive) {
396         myTextLine->setText("");
397       }
398     }
399   }
400 }
401
402
403 //********************************************************************
404 void ModuleBase_WidgetShapeSelector::activateSelection(bool toActivate)
405 {
406   if (myIsActive == toActivate)
407     return;
408   myIsActive = toActivate;
409   updateSelectionName();
410   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
411
412   if (myIsActive) {
413     connect(myWorkshop, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()));
414     QIntList aList;
415     foreach (QString aType, myShapeTypes) {
416       aList.append(shapeType(aType));
417     }
418     myWorkshop->activateSubShapesSelection(aList);
419   } else {
420     disconnect(myWorkshop, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()));
421     myWorkshop->deactivateSubShapesSelection();
422   }
423
424   // the initial code is moved here in order to clear filters, it is possible, that it is excessive and 
425   // is performed outside
426   if (myIsActive && !myObjectTypes.isEmpty()) {
427     aViewer->clearSelectionFilters();
428   }
429   SelectMgr_ListOfFilter aFilters;
430   selectionFilters(aFilters);
431   SelectMgr_ListIteratorOfListOfFilter aIt(aFilters);
432   for (; aIt.More(); aIt.Next()) {
433     const Handle(SelectMgr_Filter)& aSelFilter = aIt.Value();
434     if (myIsActive)
435       aViewer->addSelectionFilter(aSelFilter);
436     else
437       aViewer->removeSelectionFilter(aSelFilter);
438   }
439   // the internal filter should be removed by the widget deactivation, it is done historically
440   if (!myIsActive && !myObjTypeFilter.IsNull()) {
441     myObjTypeFilter.Nullify();
442   }
443 }
444
445 //********************************************************************
446 void ModuleBase_WidgetShapeSelector::selectionFilters(SelectMgr_ListOfFilter& theFilters)
447 {
448   if (!myObjectTypes.isEmpty()) {
449     myObjTypeFilter = new ModuleBase_ObjectTypesFilter(myWorkshop, myObjectTypes);
450     theFilters.Append(myObjTypeFilter);
451   }
452   // apply filters loaded from the XML definition of the widget
453   ModuleBase_FilterFactory* aFactory = myWorkshop->selectionFilters();
454   SelectMgr_ListOfFilter aFilters;
455   aFactory->filters(parentID(), attributeID(), aFilters);
456   SelectMgr_ListIteratorOfListOfFilter aIt(aFilters);
457   for (; aIt.More(); aIt.Next()) {
458     Handle(SelectMgr_Filter) aSelFilter = aIt.Value();
459     if (aSelFilter.IsNull())
460       continue;
461
462     theFilters.Append(aSelFilter);
463   }
464 }
465
466 //********************************************************************
467 void ModuleBase_WidgetShapeSelector::raisePanel() const
468 {
469   QWidget* aParent = myContainer->parentWidget();
470   QWidget* aLastPanel = 0;
471   while (!aParent->inherits("QDockWidget")) {
472     aLastPanel = aParent;
473     aParent = aParent->parentWidget();
474     if (!aParent)
475       return;
476   }
477   if (aParent->inherits("QDockWidget")) {
478     QDockWidget* aTabWgt = (QDockWidget*) aParent;
479     aTabWgt->raise();
480   }
481 }
482
483 //********************************************************************
484 void ModuleBase_WidgetShapeSelector::activateCustom()
485 {
486   activateSelection(true);
487 }
488
489 //********************************************************************
490 void ModuleBase_WidgetShapeSelector::deactivate()
491 {
492   activateSelection(false);
493 }
494
495 //********************************************************************
496 bool ModuleBase_WidgetShapeSelector::isValid(ObjectPtr theObj, std::shared_ptr<GeomAPI_Shape> theShape)
497 {
498   SessionPtr aMgr = ModelAPI_Session::get();
499   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
500   std::list<ModelAPI_Validator*> aValidators;
501   std::list<std::list<std::string> > anArguments;
502   aFactory->validators(parentID(), attributeID(), aValidators, anArguments);
503
504   // Check the type of selected object
505   std::list<ModelAPI_Validator*>::iterator aValidator = aValidators.begin();
506   bool isValid = true;
507   for (; aValidator != aValidators.end(); aValidator++) {
508     const ModelAPI_ResultValidator* aResValidator =
509         dynamic_cast<const ModelAPI_ResultValidator*>(*aValidator);
510     if (aResValidator) {
511       isValid = false;
512       if (aResValidator->isValid(theObj)) {
513         isValid = true;
514         break;
515       }
516     }
517   }
518   if (!isValid)
519     return false;
520
521   // Check the acceptability of the object as attribute
522   aValidator = aValidators.begin();
523   std::list<std::list<std::string> >::iterator aArgs = anArguments.begin();
524   for (; aValidator != aValidators.end(); aValidator++, aArgs++) {
525     const ModelAPI_RefAttrValidator* aAttrValidator =
526         dynamic_cast<const ModelAPI_RefAttrValidator*>(*aValidator);
527     if (aAttrValidator) {
528       if (!aAttrValidator->isValid(myFeature, *aArgs, theObj)) {
529         return false;
530       }
531     }
532     else {
533       const ModelAPI_ShapeValidator* aShapeValidator = 
534                                dynamic_cast<const ModelAPI_ShapeValidator*>(*aValidator);
535       if (aShapeValidator) {
536         DataPtr aData = myFeature->data();
537         AttributeSelectionPtr aSelectAttr = aData->selection(attributeID());
538         if (!aShapeValidator->isValid(myFeature, aSelectAttr, theShape)) {
539           return false;
540         }
541       }
542     }
543   }
544   return true;
545 }