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