Salome HOME
Merge branch 'Dev_1.1.0' of newgeom:newgeom.git into Dev_1.1.0
[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 #include <QFormLayout>
59
60 #include <TopExp_Explorer.hxx>
61 #include <TopoDS_Shape.hxx>
62
63 #include <memory>
64
65 #include <list>
66 #include <string>
67
68 typedef QMap<QString, TopAbs_ShapeEnum> ShapeTypes;
69 static ShapeTypes MyShapeTypes;
70
71 TopAbs_ShapeEnum ModuleBase_WidgetShapeSelector::shapeType(const QString& theType)
72 {
73   if (MyShapeTypes.count() == 0) {
74     MyShapeTypes["face"] = TopAbs_FACE;
75     MyShapeTypes["faces"] = TopAbs_FACE;
76     MyShapeTypes["vertex"] = TopAbs_VERTEX;
77     MyShapeTypes["vertices"] = TopAbs_VERTEX;
78     MyShapeTypes["wire"] = TopAbs_WIRE;
79     MyShapeTypes["edge"] = TopAbs_EDGE;
80     MyShapeTypes["edges"] = TopAbs_EDGE;
81     MyShapeTypes["shell"] = TopAbs_SHELL;
82     MyShapeTypes["solid"] = TopAbs_SOLID;
83     MyShapeTypes["solids"] = TopAbs_SOLID;
84   }
85   QString aType = theType.toLower();
86   if (MyShapeTypes.contains(aType))
87     return MyShapeTypes[aType];
88   Events_Error::send("Shape type defined in XML is not implemented!");
89   return TopAbs_SHAPE;
90 }
91
92 ModuleBase_WidgetShapeSelector::ModuleBase_WidgetShapeSelector(QWidget* theParent,
93                                                      ModuleBase_IWorkshop* theWorkshop,
94                                                      const Config_WidgetAPI* theData,
95                                                      const std::string& theParentId)
96     : ModuleBase_ModelWidget(theParent, theData, theParentId),
97       myWorkshop(theWorkshop), myIsActive(false)
98 {
99   QFormLayout* aLayout = new QFormLayout(this);
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, this);
105   if (!aLabelIcon.isEmpty())
106     myLabel->setPixmap(QPixmap(aLabelIcon));
107
108
109   QString aToolTip = QString::fromStdString(theData->widgetTooltip());
110   myTextLine = new QLineEdit(this);
111   myTextLine->setReadOnly(true);
112   myTextLine->setToolTip(aToolTip);
113   myTextLine->installEventFilter(this);
114
115   aLayout->addRow(myLabel, myTextLine);
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::storeValueCustom() 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   // Check whether the value is valid for the viewer selection filters
286   Handle(SelectMgr_EntityOwner) anOwner = theValue.owner();
287   if (!anOwner.IsNull()) {
288     SelectMgr_ListOfFilter aFilters;
289     selectionFilters(aFilters);
290     SelectMgr_ListIteratorOfListOfFilter aIt(aFilters);
291     for (; aIt.More(); aIt.Next()) {
292       const Handle(SelectMgr_Filter)& aFilter = aIt.Value();
293       if (!aFilter->IsOk(anOwner))
294         return false;
295     }
296   }
297   if (isValid(aObject, aShape)) {
298     setObject(aObject, aShape);
299     return true;
300   }
301   return false;
302 }
303
304 //********************************************************************
305 void ModuleBase_WidgetShapeSelector::setObject(ObjectPtr theObj, std::shared_ptr<GeomAPI_Shape> theShape)
306 {
307   mySelectedObject = theObj;
308   myShape = theShape;
309   if (mySelectedObject) {
310     raisePanel();
311   } 
312   updateSelectionName();
313   emit valuesChanged();
314 }
315
316 //********************************************************************
317 //bool ModuleBase_WidgetShapeSelector::acceptObjectShape(const ObjectPtr theResult) const
318 //{
319 //  ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theResult);
320 //
321 //  // Check that the shape of necessary type
322 //  std::shared_ptr<GeomAPI_Shape> aShapePtr = ModelAPI_Tools::shape(aResult);
323 //  if (!aShapePtr)
324 //    return false;
325 //  TopoDS_Shape aShape = aShapePtr->impl<TopoDS_Shape>();
326 //  if (aShape.IsNull())
327 //    return false;
328 //
329 //  TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
330 //  if (aShapeType == TopAbs_COMPOUND) {
331 //    foreach (QString aType,
332 //      myShapeTypes) {
333 //      TopExp_Explorer aEx(aShape, shapeType(aType));
334 //      if (aEx.More())
335 //        return true;
336 //    }
337 //  } else {
338 //    foreach (QString aType, myShapeTypes) {
339 //      if (shapeType(aType) == aShapeType)
340 //        return true;
341 //    }
342 //  }
343 //  return false;
344 //}
345
346 //********************************************************************
347 bool ModuleBase_WidgetShapeSelector::acceptSubShape(std::shared_ptr<GeomAPI_Shape> theShape) const
348 {
349   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
350   foreach (QString aType, myShapeTypes) {
351     if (aShape.ShapeType() == shapeType(aType))
352       return true;
353   }
354   return false;
355 }
356
357 //********************************************************************
358 bool ModuleBase_WidgetShapeSelector::acceptObjectType(const ObjectPtr theObject) const
359 {
360   // Definition of types is not obligatory. If types are not defined then
361   // it means that accepted any type
362   if (myObjectTypes.isEmpty())
363     return true;
364
365   foreach (QString aType, myObjectTypes) {
366     if (aType.toLower() == "construction") {
367       ResultConstructionPtr aConstr = 
368         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theObject);
369       return (aConstr != NULL);
370     } // ToDo: Process other types of objects
371   }
372   // Object type is defined but not found
373   return false;
374 }
375
376
377 //********************************************************************
378 void ModuleBase_WidgetShapeSelector::updateSelectionName()
379 {
380   DataPtr aData = myFeature->data();
381   bool isNameUpdated = false;
382   if (aData.get() != NULL) {
383     AttributeSelectionPtr aSelect = aData->selection(attributeID());
384     if (aSelect) {
385       myTextLine->setText(QString::fromStdString(aSelect->namingName()));
386       isNameUpdated = true;
387     }
388   }
389   if (!isNameUpdated) {
390     if (mySelectedObject) {
391       std::string aName = mySelectedObject->data()->name();
392       myTextLine->setText(QString::fromStdString(aName));
393     } else {
394       if (myIsActive) {
395         myTextLine->setText("");
396       }
397     }
398   }
399 }
400
401
402 //********************************************************************
403 void ModuleBase_WidgetShapeSelector::activateSelection(bool toActivate)
404 {
405   if (myIsActive == toActivate)
406     return;
407   myIsActive = toActivate;
408   updateSelectionName();
409   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
410
411   if (myIsActive) {
412     connect(myWorkshop, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()));
413     QIntList aList;
414     foreach (QString aType, myShapeTypes) {
415       aList.append(shapeType(aType));
416     }
417     myWorkshop->activateSubShapesSelection(aList);
418   } else {
419     disconnect(myWorkshop, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()));
420     myWorkshop->deactivateSubShapesSelection();
421   }
422
423   // the initial code is moved here in order to clear filters, it is possible, that it is excessive and 
424   // is performed outside
425   if (myIsActive && !myObjectTypes.isEmpty()) {
426     aViewer->clearSelectionFilters();
427   }
428   SelectMgr_ListOfFilter aFilters;
429   selectionFilters(aFilters);
430   SelectMgr_ListIteratorOfListOfFilter aIt(aFilters);
431   for (; aIt.More(); aIt.Next()) {
432     const Handle(SelectMgr_Filter)& aSelFilter = aIt.Value();
433     if (myIsActive)
434       aViewer->addSelectionFilter(aSelFilter);
435     else
436       aViewer->removeSelectionFilter(aSelFilter);
437   }
438   // the internal filter should be removed by the widget deactivation, it is done historically
439   if (!myIsActive && !myObjTypeFilter.IsNull()) {
440     myObjTypeFilter.Nullify();
441   }
442 }
443
444 //********************************************************************
445 void ModuleBase_WidgetShapeSelector::selectionFilters(SelectMgr_ListOfFilter& theFilters)
446 {
447   if (!myObjectTypes.isEmpty()) {
448     myObjTypeFilter = new ModuleBase_ObjectTypesFilter(myWorkshop, myObjectTypes);
449     theFilters.Append(myObjTypeFilter);
450   }
451   // apply filters loaded from the XML definition of the widget
452   ModuleBase_FilterFactory* aFactory = myWorkshop->selectionFilters();
453   SelectMgr_ListOfFilter aFilters;
454   aFactory->filters(parentID(), attributeID(), aFilters);
455   SelectMgr_ListIteratorOfListOfFilter aIt(aFilters);
456   for (; aIt.More(); aIt.Next()) {
457     Handle(SelectMgr_Filter) aSelFilter = aIt.Value();
458     if (aSelFilter.IsNull())
459       continue;
460
461     theFilters.Append(aSelFilter);
462   }
463 }
464
465 //********************************************************************
466 void ModuleBase_WidgetShapeSelector::raisePanel() const
467 {
468   QWidget* aParent = this->parentWidget();
469   QWidget* aLastPanel = 0;
470   while (!aParent->inherits("QDockWidget")) {
471     aLastPanel = aParent;
472     aParent = aParent->parentWidget();
473     if (!aParent)
474       return;
475   }
476   if (aParent->inherits("QDockWidget")) {
477     QDockWidget* aTabWgt = (QDockWidget*) aParent;
478     aTabWgt->raise();
479   }
480 }
481
482 //********************************************************************
483 void ModuleBase_WidgetShapeSelector::activateCustom()
484 {
485   activateSelection(true);
486 }
487
488 //********************************************************************
489 void ModuleBase_WidgetShapeSelector::deactivate()
490 {
491   activateSelection(false);
492 }
493
494 //********************************************************************
495 bool ModuleBase_WidgetShapeSelector::isValid(ObjectPtr theObj, std::shared_ptr<GeomAPI_Shape> theShape)
496 {
497   SessionPtr aMgr = ModelAPI_Session::get();
498   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
499   std::list<ModelAPI_Validator*> aValidators;
500   std::list<std::list<std::string> > anArguments;
501   aFactory->validators(parentID(), attributeID(), aValidators, anArguments);
502
503   // Check the type of selected object
504   std::list<ModelAPI_Validator*>::iterator aValidator = aValidators.begin();
505   bool isValid = true;
506   for (; aValidator != aValidators.end(); aValidator++) {
507     const ModelAPI_ResultValidator* aResValidator =
508         dynamic_cast<const ModelAPI_ResultValidator*>(*aValidator);
509     if (aResValidator) {
510       isValid = false;
511       if (aResValidator->isValid(theObj)) {
512         isValid = true;
513         break;
514       }
515     }
516   }
517   if (!isValid)
518     return false;
519
520   // Check the acceptability of the object as attribute
521   aValidator = aValidators.begin();
522   std::list<std::list<std::string> >::iterator aArgs = anArguments.begin();
523   for (; aValidator != aValidators.end(); aValidator++, aArgs++) {
524     const ModelAPI_RefAttrValidator* aAttrValidator =
525         dynamic_cast<const ModelAPI_RefAttrValidator*>(*aValidator);
526     if (aAttrValidator) {
527       if (!aAttrValidator->isValid(myFeature, *aArgs, theObj)) {
528         return false;
529       }
530     }
531     else {
532       const ModelAPI_ShapeValidator* aShapeValidator = 
533                                dynamic_cast<const ModelAPI_ShapeValidator*>(*aValidator);
534       if (aShapeValidator) {
535         DataPtr aData = myFeature->data();
536         AttributeSelectionPtr aSelectAttr = aData->selection(attributeID());
537         if (!aShapeValidator->isValid(myFeature, aSelectAttr, theShape)) {
538           return false;
539         }
540       }
541     }
542   }
543   return true;
544 }