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