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