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