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