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