Salome HOME
Issue #336 Create/Edit Line -filter for first and last point fields
[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)
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
124 //********************************************************************
125 ModuleBase_WidgetShapeSelector::~ModuleBase_WidgetShapeSelector()
126 {
127   activateSelection(false);
128 }
129
130 //********************************************************************
131 bool ModuleBase_WidgetShapeSelector::storeValue() const
132 {
133   FeaturePtr aSelectedFeature = ModelAPI_Feature::feature(mySelectedObject);
134   if (aSelectedFeature == myFeature)  // In order to avoid selection of the same object
135     return false;
136
137   DataPtr aData = myFeature->data();
138   AttributeReferencePtr aRef = aData->reference(attributeID());
139   if (aRef) {
140     ObjectPtr aObject = aRef->value();
141     if (!(aObject && aObject->isSame(mySelectedObject))) {
142       aRef->setValue(mySelectedObject);
143       updateObject(myFeature);
144       return true;
145     }
146   } else {
147     AttributeRefAttrPtr aRefAttr = aData->refattr(attributeID());
148     if (aRefAttr) {
149       ObjectPtr aObject = aRefAttr->object();
150       if (!(aObject && aObject->isSame(mySelectedObject))) {
151         aRefAttr->setObject(mySelectedObject);
152         updateObject(myFeature);
153         return true;
154       }
155     } else {
156       AttributeSelectionPtr aSelectAttr = aData->selection(attributeID());
157       ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(mySelectedObject);
158       if (aSelectAttr && aBody && (myShape.get() != NULL)) {
159         aSelectAttr->setValue(aBody, myShape);
160         updateObject(myFeature);
161         return true;
162       }
163     }
164   }
165   return false;
166 }
167
168 //********************************************************************
169 void ModuleBase_WidgetShapeSelector::clearAttribute()
170 {
171   DataPtr aData = myFeature->data();
172   AttributeSelectionPtr aSelect = aData->selection(attributeID());
173   if (aSelect) {
174     aSelect->setValue(ResultPtr(), std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape()));
175     return;
176   }
177   AttributeRefAttrPtr aRefAttr = aData->refattr(attributeID());
178   if (aRefAttr) {
179     aRefAttr->setObject(ObjectPtr());
180     return;
181   }
182   AttributeReferencePtr aRef = aData->reference(attributeID());
183   if (aRef) {
184     aRef->setObject(ObjectPtr());
185   }
186 }
187
188 //********************************************************************
189 bool ModuleBase_WidgetShapeSelector::restoreValue()
190 {
191   DataPtr aData = myFeature->data();
192   bool isBlocked = this->blockSignals(true);
193
194   AttributeSelectionPtr aSelect = aData->selection(attributeID());
195   if (aSelect) {
196     mySelectedObject = aSelect->context();
197     myShape = aSelect->value();
198   } else {
199     AttributeRefAttrPtr aRefAttr = aData->refattr(attributeID());
200     if (aRefAttr) {
201       mySelectedObject = aRefAttr->object();
202     } else {
203       AttributeReferencePtr aRef = aData->reference(attributeID());
204       if (aRef) {
205         mySelectedObject = aRef->value();
206       }
207     }
208   }
209   updateSelectionName();
210
211   this->blockSignals(isBlocked);
212   return true;
213 }
214
215 //********************************************************************
216 QList<QWidget*> ModuleBase_WidgetShapeSelector::getControls() const
217 {
218   QList<QWidget*> aControls;
219   aControls.append(myTextLine);
220   return aControls;
221 }
222
223 //********************************************************************
224 void ModuleBase_WidgetShapeSelector::onSelectionChanged()
225 {
226   // In order to make reselection possible
227   // TODO: check with MPV clearAttribute();
228
229   //QObjectPtrList aObjects = myWorkshop->selection()->selectedPresentations();
230   QList<ModuleBase_ViewerPrs> aSelected = myWorkshop->selection()->getSelected();
231   if (aSelected.size() > 0) {
232     if (setSelection(aSelected.first()))
233       emit focusOutWidget(this);
234   }
235 }
236
237 //********************************************************************
238 bool ModuleBase_WidgetShapeSelector::setSelection(ModuleBase_ViewerPrs theValue)
239 {
240   ObjectPtr aObject = theValue.object();
241   if ((!mySelectedObject) && (!aObject))
242     return false;
243
244   // Check that the selected object is result (others can not be accepted)
245   ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObject);
246   if (!aRes)
247     return false;
248
249   if (myFeature) {
250     // We can not select a result of our feature
251     const std::list<std::shared_ptr<ModelAPI_Result>>& aResList = myFeature->results();
252     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aIt;
253     for (aIt = aResList.cbegin(); aIt != aResList.cend(); ++aIt) {
254       if ((*aIt) == aRes)
255         return false;
256     }
257   }
258   // Check that object belongs to active document or PartSet
259   DocumentPtr aDoc = aRes->document();
260   SessionPtr aMgr = ModelAPI_Session::get();
261   if (!(aDoc == aMgr->activeDocument()) && !(aDoc == aMgr->moduleDocument()))
262     return false;
263
264   // Check that the result has a shape
265   GeomShapePtr aShape = ModelAPI_Tools::shape(aRes);
266   if (!aShape)
267     return false;
268
269   /// Check that object has acceptable type
270   if (!acceptObjectType(aObject)) 
271     return false;
272
273   // Get sub-shapes from local selection
274   if (!theValue.shape().IsNull()) {
275     aShape = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape());
276     aShape->setImpl(new TopoDS_Shape(theValue.shape()));
277   }
278
279   // Check that the selection corresponds to selection type
280   if (!acceptSubShape(aShape))
281     return false;
282 //  if (!acceptObjectShape(aObject))
283 //      return false;
284
285   if (isValid(aObject, aShape)) {
286     setObject(aObject, aShape);
287     return true;
288   }
289   return false;
290 }
291
292 //********************************************************************
293 void ModuleBase_WidgetShapeSelector::setObject(ObjectPtr theObj, std::shared_ptr<GeomAPI_Shape> theShape)
294 {
295   mySelectedObject = theObj;
296   myShape = theShape;
297   if (mySelectedObject) {
298     raisePanel();
299   } 
300   updateSelectionName();
301   emit valuesChanged();
302 }
303
304 //********************************************************************
305 //bool ModuleBase_WidgetShapeSelector::acceptObjectShape(const ObjectPtr theResult) const
306 //{
307 //  ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theResult);
308 //
309 //  // Check that the shape of necessary type
310 //  std::shared_ptr<GeomAPI_Shape> aShapePtr = ModelAPI_Tools::shape(aResult);
311 //  if (!aShapePtr)
312 //    return false;
313 //  TopoDS_Shape aShape = aShapePtr->impl<TopoDS_Shape>();
314 //  if (aShape.IsNull())
315 //    return false;
316 //
317 //  TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
318 //  if (aShapeType == TopAbs_COMPOUND) {
319 //    foreach (QString aType,
320 //      myShapeTypes) {
321 //      TopExp_Explorer aEx(aShape, shapeType(aType));
322 //      if (aEx.More())
323 //        return true;
324 //    }
325 //  } else {
326 //    foreach (QString aType, myShapeTypes) {
327 //      if (shapeType(aType) == aShapeType)
328 //        return true;
329 //    }
330 //  }
331 //  return false;
332 //}
333
334 //********************************************************************
335 bool ModuleBase_WidgetShapeSelector::acceptSubShape(std::shared_ptr<GeomAPI_Shape> theShape) const
336 {
337   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
338   foreach (QString aType, myShapeTypes) {
339     if (aShape.ShapeType() == shapeType(aType))
340       return true;
341   }
342   return false;
343 }
344
345 //********************************************************************
346 bool ModuleBase_WidgetShapeSelector::acceptObjectType(const ObjectPtr theObject) const
347 {
348   // Definition of types is not obligatory. If types are not defined then
349   // it means that accepted any type
350   if (myObjectTypes.isEmpty())
351     return true;
352
353   foreach (QString aType, myObjectTypes) {
354     if (aType.toLower() == "construction") {
355       ResultConstructionPtr aConstr = 
356         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theObject);
357       return (aConstr != NULL);
358     } // ToDo: Process other types of objects
359   }
360   // Object type is defined but not found
361   return false;
362 }
363
364
365 //********************************************************************
366 void ModuleBase_WidgetShapeSelector::updateSelectionName()
367 {
368   DataPtr aData = myFeature->data();
369   bool isNameUpdated = false;
370   if (aData.get() != NULL) {
371     AttributeSelectionPtr aSelect = aData->selection(attributeID());
372     if (aSelect) {
373       myTextLine->setText(QString::fromStdString(aSelect->namingName()));
374       isNameUpdated = true;
375     }
376   }
377   if (!isNameUpdated) {
378     if (mySelectedObject) {
379       std::string aName = mySelectedObject->data()->name();
380       myTextLine->setText(QString::fromStdString(aName));
381     } else {
382       if (myIsActive) {
383         myTextLine->setText("");
384       }
385     }
386   }
387 }
388
389
390 //********************************************************************
391 void ModuleBase_WidgetShapeSelector::activateSelection(bool toActivate)
392 {
393   if (myIsActive == toActivate)
394     return;
395   myIsActive = toActivate;
396   updateSelectionName();
397   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
398
399   if (myIsActive) {
400     connect(myWorkshop, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()));
401     QIntList aList;
402     foreach (QString aType, myShapeTypes) {
403       aList.append(shapeType(aType));
404     }
405     myWorkshop->activateSubShapesSelection(aList);
406     if (!myObjectTypes.isEmpty()) {
407       myObjTypeFilter = new ModuleBase_ObjectTypesFilter(myWorkshop, myObjectTypes);
408       aViewer->clearSelectionFilters();
409       aViewer->addSelectionFilter(myObjTypeFilter);
410     }
411   } else {
412     disconnect(myWorkshop, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()));
413     if (!myObjTypeFilter.IsNull()) {
414       aViewer->removeSelectionFilter(myObjTypeFilter);
415       myObjTypeFilter.Nullify();
416     }
417     myWorkshop->deactivateSubShapesSelection();
418   }
419   // apply filters loaded from the XML definition of the widget
420   ModuleBase_FilterFactory* aFactory = myWorkshop->selectionFilters();
421   SelectMgr_ListOfFilter aFilters;
422   aFactory->filters(parentID(), attributeID(), aFilters);
423   SelectMgr_ListIteratorOfListOfFilter aIt(aFilters);
424   for (; aIt.More(); aIt.Next()) {
425     Handle(SelectMgr_Filter) aSelFilter = aIt.Value();
426     if (aSelFilter.IsNull())
427       continue;
428
429     //Handle(ModuleBase_Filter) aFilter = Handle(ModuleBase_Filter)::DownCast(aIt.Value());
430     //if (aFilter.IsNull())
431     //  continue;
432     if (myIsActive)
433       aViewer->addSelectionFilter(aSelFilter);
434     else
435       aViewer->removeSelectionFilter(aSelFilter);
436   }
437 }
438
439 //********************************************************************
440 void ModuleBase_WidgetShapeSelector::raisePanel() const
441 {
442   QWidget* aParent = myContainer->parentWidget();
443   QWidget* aLastPanel = 0;
444   while (!aParent->inherits("QDockWidget")) {
445     aLastPanel = aParent;
446     aParent = aParent->parentWidget();
447     if (!aParent)
448       return;
449   }
450   if (aParent->inherits("QDockWidget")) {
451     QDockWidget* aTabWgt = (QDockWidget*) aParent;
452     aTabWgt->raise();
453   }
454 }
455
456 //********************************************************************
457 void ModuleBase_WidgetShapeSelector::activate()
458 {
459   activateSelection(true);
460 }
461
462 //********************************************************************
463 void ModuleBase_WidgetShapeSelector::deactivate()
464 {
465   activateSelection(false);
466 }
467
468 //********************************************************************
469 bool ModuleBase_WidgetShapeSelector::isValid(ObjectPtr theObj, std::shared_ptr<GeomAPI_Shape> theShape)
470 {
471   SessionPtr aMgr = ModelAPI_Session::get();
472   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
473   std::list<ModelAPI_Validator*> aValidators;
474   std::list<std::list<std::string> > anArguments;
475   aFactory->validators(parentID(), attributeID(), aValidators, anArguments);
476
477   // Check the type of selected object
478   std::list<ModelAPI_Validator*>::iterator aValidator = aValidators.begin();
479   bool isValid = true;
480   for (; aValidator != aValidators.end(); aValidator++) {
481     const ModelAPI_ResultValidator* aResValidator =
482         dynamic_cast<const ModelAPI_ResultValidator*>(*aValidator);
483     if (aResValidator) {
484       isValid = false;
485       if (aResValidator->isValid(theObj)) {
486         isValid = true;
487         break;
488       }
489     }
490   }
491   if (!isValid)
492     return false;
493
494   // Check the acceptability of the object as attribute
495   aValidator = aValidators.begin();
496   std::list<std::list<std::string> >::iterator aArgs = anArguments.begin();
497   for (; aValidator != aValidators.end(); aValidator++, aArgs++) {
498     const ModelAPI_RefAttrValidator* aAttrValidator =
499         dynamic_cast<const ModelAPI_RefAttrValidator*>(*aValidator);
500     if (aAttrValidator) {
501       if (!aAttrValidator->isValid(myFeature, *aArgs, theObj)) {
502         return false;
503       }
504     }
505   }
506   return true;
507 }