Salome HOME
886c5765890cf95cbca239ddccbec35bbaf0e6df
[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     setSelection(aSelected.first());
253 }
254
255 //********************************************************************
256 bool ModuleBase_WidgetShapeSelector::setSelection(ModuleBase_ViewerPrs theValue)
257 {
258   ObjectPtr aObject = theValue.object();
259   if ((!mySelectedObject) && (!aObject))
260     return false;
261
262   // Check that the selected object is result (others can not be accepted)
263   ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObject);
264   if (!aRes)
265     return false;
266
267   if (myFeature) {
268     // We can not select a result of our feature
269     const std::list<std::shared_ptr<ModelAPI_Result>>& aResList = myFeature->results();
270     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aIt;
271     for (aIt = aResList.cbegin(); aIt != aResList.cend(); ++aIt) {
272       if ((*aIt) == aRes)
273         return false;
274     }
275   }
276   // Check that object belongs to active document or PartSet
277   DocumentPtr aDoc = aRes->document();
278   SessionPtr aMgr = ModelAPI_Session::get();
279   if (!(aDoc == aMgr->activeDocument()) && !(aDoc == aMgr->moduleDocument()))
280     return false;
281
282   // Check that the result has a shape
283   GeomShapePtr aShape = ModelAPI_Tools::shape(aRes);
284   if (!aShape)
285     return false;
286
287   /// Check that object has acceptable type
288   if (!acceptObjectType(aObject)) 
289     return false;
290
291   // Get sub-shapes from local selection
292   if (myUseSubShapes) {
293     if (!theValue.shape().IsNull()) {
294       aShape = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape());
295       aShape->setImpl(new TopoDS_Shape(theValue.shape()));
296     }
297   }
298
299   // Check that the selection corresponds to selection type
300   if (myUseSubShapes) {
301     if (!acceptSubShape(aShape))
302       return false;
303   } else {
304     if (!acceptObjectShape(aObject))
305       return false;
306   }
307   if (isValid(aObject, aShape)) {
308     setObject(aObject, aShape);
309     emit focusOutWidget(this);
310     return true;
311   }
312   return false;
313 }
314
315 //********************************************************************
316 void ModuleBase_WidgetShapeSelector::setObject(ObjectPtr theObj, std::shared_ptr<GeomAPI_Shape> theShape)
317 {
318   mySelectedObject = theObj;
319   myShape = theShape;
320   if (mySelectedObject) {
321     raisePanel();
322   } 
323   updateSelectionName();
324   emit valuesChanged();
325 }
326
327 //********************************************************************
328 bool ModuleBase_WidgetShapeSelector::acceptObjectShape(const ObjectPtr theResult) const
329 {
330   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theResult);
331
332   // Check that the shape of necessary type
333   std::shared_ptr<GeomAPI_Shape> aShapePtr = ModelAPI_Tools::shape(aResult);
334   if (!aShapePtr)
335     return false;
336   TopoDS_Shape aShape = aShapePtr->impl<TopoDS_Shape>();
337   if (aShape.IsNull())
338     return false;
339
340   TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
341   if (aShapeType == TopAbs_COMPOUND) {
342     foreach (QString aType, myShapeTypes) {
343       TopExp_Explorer aEx(aShape, shapeType(aType));
344       if (aEx.More())
345         return true;
346     }
347   } else {
348     foreach (QString aType, myShapeTypes) {
349       if (shapeType(aType) == aShapeType)
350         return true;
351     }
352   }
353   return false;
354 }
355
356 //********************************************************************
357 bool ModuleBase_WidgetShapeSelector::acceptSubShape(std::shared_ptr<GeomAPI_Shape> theShape) const
358 {
359   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
360   foreach (QString aType, myShapeTypes) {
361     if (aShape.ShapeType() == shapeType(aType))
362       return true;
363   }
364   return false;
365 }
366
367 //********************************************************************
368 bool ModuleBase_WidgetShapeSelector::acceptObjectType(const ObjectPtr theObject) const
369 {
370   // Definition of types is not obligatory. If types are not defined then
371   // it means that accepted any type
372   if (myObjectTypes.isEmpty())
373     return true;
374
375   foreach (QString aType, myObjectTypes) {
376     if (aType.toLower() == "construction") {
377       ResultConstructionPtr aConstr = 
378         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theObject);
379       return (aConstr != NULL);
380     } // ToDo: Process other types of objects
381   }
382   // Object type is defined but not found
383   return false;
384 }
385
386
387 //********************************************************************
388 void ModuleBase_WidgetShapeSelector::updateSelectionName()
389 {
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 void ModuleBase_WidgetShapeSelector::activateSelection(bool toActivate)
403 {
404   if (myIsActive == toActivate)
405     return;
406   myIsActive = toActivate;
407   updateSelectionName();
408   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
409
410   if (myIsActive) {
411     connect(myWorkshop, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()));
412     if (myUseSubShapes) {
413
414       QIntList aList;
415       foreach (QString aType, myShapeTypes)
416         aList.append(shapeType(aType));
417       myWorkshop->activateSubShapesSelection(aList);
418       if (!myObjectTypes.isEmpty()) {
419         myObjTypeFilter = new ModuleBase_ObjectTypesFilter(myWorkshop, myObjectTypes);
420         aViewer->clearSelectionFilters();
421         aViewer->addSelectionFilter(myObjTypeFilter);
422       }
423     }
424   } else {
425     disconnect(myWorkshop, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()));
426     if (myUseSubShapes) {
427       if (!myObjTypeFilter.IsNull()) {
428         aViewer->removeSelectionFilter(myObjTypeFilter);
429         myObjTypeFilter.Nullify();
430       }
431       myWorkshop->deactivateSubShapesSelection();
432     }
433   }
434
435   /*ModuleBase_FilterFactory* aFactory = myWorkshop->selectionFilters();
436   const SelectMgr_ListOfFilter& aFilters = aFactory->filters(parentID(), attributeID());
437   SelectMgr_ListIteratorOfListOfFilter aIt(aFilters);
438   for (; aIt.More(); aIt.Next()) {
439     Handle(ModuleBase_Filter) aFilter = Handle(ModuleBase_Filter)::DownCast(aIt.Value());
440     if (myIsActive)
441       aViewer->addSelectionFilter(aFilter);
442     else
443       aViewer->removeSelectionFilter(aFilter);
444   }*/
445 }
446
447 //********************************************************************
448 void ModuleBase_WidgetShapeSelector::raisePanel() const
449 {
450   QWidget* aParent = myContainer->parentWidget();
451   QWidget* aLastPanel = 0;
452   while (!aParent->inherits("QDockWidget")) {
453     aLastPanel = aParent;
454     aParent = aParent->parentWidget();
455     if (!aParent)
456       return;
457   }
458   if (aParent->inherits("QDockWidget")) {
459     QDockWidget* aTabWgt = (QDockWidget*) aParent;
460     aTabWgt->raise();
461   }
462 }
463
464 //********************************************************************
465 //bool ModuleBase_WidgetShapeSelector::setSelection(ModuleBase_ViewerPrs theValue)
466 //{
467 //  if (theValue.object()) {
468 //    ObjectPtr aObject = theValue.object();
469 //    if (acceptObjectShape(aObject)) {
470 //      setObject(aObject);
471 //      return true;
472 //    }
473 //  }
474 //  return false;
475 //}
476
477 //********************************************************************
478 void ModuleBase_WidgetShapeSelector::activate()
479 {
480   activateSelection(true);
481 }
482
483 //********************************************************************
484 void ModuleBase_WidgetShapeSelector::deactivate()
485 {
486   activateSelection(false);
487 }
488
489 //********************************************************************
490 bool ModuleBase_WidgetShapeSelector::isValid(ObjectPtr theObj, std::shared_ptr<GeomAPI_Shape> theShape)
491 {
492   SessionPtr aMgr = ModelAPI_Session::get();
493   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
494   std::list<ModelAPI_Validator*> aValidators;
495   std::list<std::list<std::string> > anArguments;
496   aFactory->validators(parentID(), attributeID(), aValidators, anArguments);
497
498   // Check the type of selected object
499   std::list<ModelAPI_Validator*>::iterator aValidator = aValidators.begin();
500   bool isValid = true;
501   for (; aValidator != aValidators.end(); aValidator++) {
502     const ModelAPI_ResultValidator* aResValidator =
503         dynamic_cast<const ModelAPI_ResultValidator*>(*aValidator);
504     if (aResValidator) {
505       isValid = false;
506       if (aResValidator->isValid(theObj)) {
507         isValid = true;
508         break;
509       }
510     }
511   }
512   if (!isValid)
513     return false;
514
515   // Check the acceptability of the object as attribute
516   aValidator = aValidators.begin();
517   std::list<std::list<std::string> >::iterator aArgs = anArguments.begin();
518   for (; aValidator != aValidators.end(); aValidator++, aArgs++) {
519     const ModelAPI_RefAttrValidator* aAttrValidator =
520         dynamic_cast<const ModelAPI_RefAttrValidator*>(*aValidator);
521     if (aAttrValidator) {
522       if (!aAttrValidator->isValid(myFeature, *aArgs, theObj)) {
523         return false;
524       }
525     }
526   }
527   return true;
528 }