1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
3 // File: ModuleBase_Tools.cpp
4 // Created: 11 July 2014
5 // Author: Vitaly Smetannikov
7 #include "ModuleBase_Tools.h"
9 #include <ModuleBase_ParamIntSpinBox.h>
10 #include <ModuleBase_ParamSpinBox.h>
11 #include <ModuleBase_WidgetFactory.h>
12 #include <ModuleBase_IWorkshop.h>
13 #include <ModuleBase_IModule.h>
14 #include <ModuleBase_IconFactory.h>
16 #include <ModelAPI_Attribute.h>
17 #include <ModelAPI_AttributeRefAttr.h>
18 #include <ModelAPI_AttributeReference.h>
19 #include <ModelAPI_AttributeSelection.h>
20 #include <ModelAPI_AttributeSelectionList.h>
21 #include <ModelAPI_AttributeRefList.h>
22 #include <ModelAPI_AttributeRefAttrList.h>
23 #include <ModelAPI_ResultPart.h>
24 #include <Events_Loop.h>
26 #include <ModelAPI_Data.h>
27 #include <ModelAPI_Result.h>
28 #include <ModelAPI_ResultCompSolid.h>
29 #include <ModelAPI_ResultParameter.h>
30 #include <ModelAPI_Tools.h>
31 #include <ModelAPI_Session.h>
32 #include <ModelAPI_Events.h>
34 #include <TopoDS_Iterator.hxx>
36 #include <GeomDataAPI_Point2D.h>
37 #include <Events_Error.h>
39 #include <Config_PropManager.h>
45 #include <QDoubleSpinBox>
46 #include <QGraphicsDropShadowEffect>
48 #include <QApplication>
49 #include <QMessageBox>
55 const double tolerance = 1e-7;
57 //#define DEBUG_ACTIVATE_WINDOW
58 //#define DEBUG_SET_FOCUS
59 //#define DEBUG_SELECTION_INFO
61 #ifdef DEBUG_SELECTION_INFO
62 #include <ModuleBase_ISelection.h>
63 #include <ModuleBase_ViewerPrs.h>
65 #include <AIS_InteractiveContext.hxx>
66 #include <AIS_ListOfInteractive.hxx>
67 #include <AIS_ListIteratorOfListOfInteractive.hxx>
68 #include <AIS_Shape.hxx>
69 #include <TopoDS_Shape.hxx>
70 #include <AIS_LocalContext.hxx>
71 #include <NCollection_List.hxx>
72 #include <StdSelect_BRepOwner.hxx>
73 #include <TColStd_ListOfInteger.hxx>
74 #include <TColStd_ListIteratorOfListOfInteger.hxx>
77 namespace ModuleBase_Tools {
79 //******************************************************************
81 //******************************************************************
83 void adjustMargins(QWidget* theWidget)
87 adjustMargins(theWidget->layout());
90 void adjustMargins(QLayout* theLayout)
94 theLayout->setContentsMargins(2, 5, 2, 5);
95 theLayout->setSpacing(4);
98 void zeroMargins(QWidget* theWidget)
102 zeroMargins(theWidget->layout());
105 void zeroMargins(QLayout* theLayout)
109 theLayout->setContentsMargins(0, 0, 0, 0);
110 theLayout->setSpacing(5);
113 void activateWindow(QWidget* theWidget, const QString& theInfo)
115 theWidget->activateWindow();
117 #ifdef DEBUG_ACTIVATE_WINDOW
118 qDebug(QString("activateWindow: %1").arg(theInfo).toStdString().c_str());
122 void setFocus(QWidget* theWidget, const QString& theInfo)
124 theWidget->setFocus();
126 #ifdef DEBUG_SET_FOCUS
127 qDebug(QString("setFocus: %1").arg(theInfo).toStdString().c_str());
131 void setShadowEffect(QWidget* theWidget, const bool isSetEffect)
134 QGraphicsDropShadowEffect* aGlowEffect = new QGraphicsDropShadowEffect();
135 aGlowEffect->setOffset(.0);
136 aGlowEffect->setBlurRadius(10.0);
137 aGlowEffect->setColor(QColor(0, 170, 255)); // Light-blue color, #00AAFF
138 theWidget->setGraphicsEffect(aGlowEffect);
141 QGraphicsEffect* anEffect = theWidget->graphicsEffect();
143 anEffect->deleteLater();
144 theWidget->setGraphicsEffect(NULL);
148 QPixmap composite(const QString& theAdditionalIcon, const QString& theIcon)
150 QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
151 QImage anAditional(theAdditionalIcon);
156 int anAddWidth = anAditional.width();
157 int anAddHeight = anAditional.height();
159 int aWidth = anIcon.width();
160 int aHeight = anIcon.height();
162 int aStartWidthPos = aWidth - anAddWidth - 1;
163 int aStartHeightPos = aHeight - anAddHeight - 1;
165 for (int i = 0; i < anAddWidth && i + aStartWidthPos < aWidth; i++)
167 for (int j = 0; j < anAddHeight && j + aStartHeightPos < aHeight; j++)
169 if (qAlpha(anAditional.pixel(i, j)) > 0)
170 anIcon.setPixel(i + aStartWidthPos, j + aStartHeightPos, anAditional.pixel(i, j));
173 return QPixmap::fromImage(anIcon);
176 QPixmap lighter(const QString& theIcon, const int theLighterValue)
178 QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
182 QImage aResult = ModuleBase_IconFactory::loadImage(theIcon);
183 for (int i = 0; i < anIcon.width(); i++)
185 for (int j = 0; j < anIcon.height(); j++)
187 QRgb anRgb = anIcon.pixel(i, j);
188 QColor aPixelColor(qRed(anRgb), qGreen(anRgb), qBlue(anRgb),
189 qAlpha(aResult.pixel(i, j)));
191 QColor aLighterColor = aPixelColor.lighter(theLighterValue);
192 aResult.setPixel(i, j, qRgba(aLighterColor.red(), aLighterColor.green(),
193 aLighterColor.blue(), aLighterColor.alpha()));
196 return QPixmap::fromImage(aResult);
199 void setSpinText(ModuleBase_ParamSpinBox* theSpin, const QString& theText)
201 if (theSpin->text() == theText)
203 // In order to avoid extra text setting because it will
204 // reset cursor position in control
205 bool isBlocked = theSpin->blockSignals(true);
206 theSpin->setText(theText);
207 theSpin->blockSignals(isBlocked);
210 void setSpinValue(QDoubleSpinBox* theSpin, double theValue)
212 if (fabs(theSpin->value() - theValue) < tolerance)
214 bool isBlocked = theSpin->blockSignals(true);
215 theSpin->setValue(theValue);
216 theSpin->blockSignals(isBlocked);
219 void setSpinValue(ModuleBase_ParamSpinBox* theSpin, double theValue)
221 if (fabs(theSpin->value() - theValue) < tolerance)
223 bool isBlocked = theSpin->blockSignals(true);
224 theSpin->setValue(theValue);
225 theSpin->blockSignals(isBlocked);
228 void setSpinText(ModuleBase_ParamIntSpinBox* theSpin, const QString& theText)
230 // In order to avoid extra text setting because it will
231 // reset cursor position in control
232 if (theSpin->text() == theText)
234 bool isBlocked = theSpin->blockSignals(true);
235 theSpin->setText(theText);
236 theSpin->blockSignals(isBlocked);
239 void setSpinValue(ModuleBase_ParamIntSpinBox* theSpin, int theValue)
241 if (theSpin->value() == theValue)
243 bool isBlocked = theSpin->blockSignals(true);
244 theSpin->setValue(theValue);
245 theSpin->blockSignals(isBlocked);
248 QAction* createAction(const QIcon& theIcon, const QString& theText,
249 QObject* theParent, const QObject* theReceiver,
250 const char* theMember, const QString& theToolTip,
251 const QString& theStatusTip)
253 QAction* anAction = new QAction(theIcon, theText, theParent);
254 anAction->setToolTip(theToolTip.isEmpty() ? theText : theToolTip);
255 anAction->setStatusTip(!theStatusTip.isEmpty() ? theStatusTip :
256 (!theToolTip.isEmpty() ? theToolTip : theText));
258 QObject::connect(anAction, SIGNAL(triggered(bool)), theReceiver, theMember);
263 QString objectInfo(const ObjectPtr& theObj, const bool isUseAttributesInfo)
265 QString aFeatureStr = "feature";
269 std::ostringstream aPtrStr;
270 aPtrStr << "[" << theObj.get() << "]";
272 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theObj);
273 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
275 aFeatureStr.append(QString("(result%1)").arg(aPtrStr.str().c_str()).toStdString() .c_str());
276 if (aRes->isDisabled())
277 aFeatureStr.append("[disabled]");
278 if (aRes->isConcealed())
279 aFeatureStr.append("[concealed]");
280 if (ModelAPI_Tools::hasSubResults(aRes))
281 aFeatureStr.append("[hasSubResults]");
283 aFeature = ModelAPI_Feature::feature(aRes);
286 aFeatureStr.append(aPtrStr.str().c_str());
288 if (aFeature.get()) {
289 aFeatureStr.append(QString(": %1").arg(aFeature->getKind().c_str()).toStdString().c_str());
290 if (aFeature->data()->isValid()) {
291 aFeatureStr.append(QString(", name=%1").arg(theObj->data()->name().c_str()).toStdString()
294 if (isUseAttributesInfo) {
295 std::list<AttributePtr> anAttrs = aFeature->data()->attributes("");
296 std::list<AttributePtr>::const_iterator anIt = anAttrs.begin(), aLast = anAttrs.end();
298 for(; anIt != aLast; anIt++) {
299 AttributePtr anAttr = *anIt;
300 QString aValue = "not defined";
301 std::string aType = anAttr->attributeType();
302 if (aType == GeomDataAPI_Point2D::typeId()) {
303 std::shared_ptr<GeomDataAPI_Point2D> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
306 aValue = QString("(%1, %2)").arg(aPoint->x()).arg(aPoint->y());
308 else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
311 aValues.push_back(QString("%1: %2").arg(anAttr->id().c_str()).arg(aValue).toStdString().c_str());
313 if (!aValues.empty())
314 aFeatureStr.append(QString(", attributes: %1").arg(aValues.join(", ").toStdString().c_str()));
321 #ifdef DEBUG_SELECTION_INFO
322 QString getShapeTypeInfo(const int theType)
324 QString anInfo = "Undefined";
326 case TopAbs_COMPOUND: anInfo = "compound"; break;
327 case TopAbs_COMPSOLID: anInfo = "compsolid"; break;
328 case TopAbs_SOLID: anInfo = "solid"; break;
329 case TopAbs_SHELL: anInfo = "shell"; break;
330 case TopAbs_FACE: anInfo = "face"; break;
331 case TopAbs_WIRE: anInfo = "wire"; break;
332 case TopAbs_EDGE: anInfo = "edge"; break;
333 case TopAbs_VERTEX: anInfo = "vertex"; break;
334 case TopAbs_SHAPE: anInfo = "shape"; break;
340 QString getModeInfo(const int theMode)
342 QString anInfo = "Undefined";
344 case 0: anInfo = "SHAPE(0)"; break;
345 case 1: anInfo = "VERTEX(1)"; break;
346 case 2: anInfo = "EDGE(2)"; break;
347 case 3: anInfo = "WIRE(3)"; break;
348 case 4: anInfo = "FACE(4)"; break;
349 case 5: anInfo = "SHELL(5)"; break;
350 case 6: anInfo = "SOLID(6)"; break;
351 case 7: anInfo = "COMPSOLID(7)"; break;
352 case 8: anInfo = "COMPOUND(8)"; break;
353 case 100: anInfo = "Sel_Mode_First(100)"; break; //SketcherPrs_Tools
354 case 101: anInfo = "Sel_Constraint(101)"; break;
355 case 102: anInfo = "Sel_Dimension_All(102)"; break;
356 case 103: anInfo = "Sel_Dimension_Line(103)"; break;
357 case 104: anInfo = "Sel_Dimension_Text(104)"; break;
363 QString displayedInteractiveObjects(Handle(AIS_InteractiveContext)& theContext,
364 const bool theShapeInfoOnly = true)
366 if (theContext.IsNull())
368 AIS_ListOfInteractive aListOfIO;
369 theContext->DisplayedObjects(aListOfIO, false);
370 QStringList anObjects;
371 AIS_ListIteratorOfListOfInteractive aIt;
372 for (aIt.Initialize(aListOfIO); aIt.More(); aIt.Next()) {
373 Handle(AIS_InteractiveObject) anAISIO = aIt.Value();
374 Handle(AIS_Shape) aShapePrs = Handle(AIS_Shape)::DownCast(anAISIO);
375 if (theShapeInfoOnly && aShapePrs.IsNull())
378 QString anInfo = "IO";
379 std::ostringstream aPtrStr;
380 aPtrStr << "[" << anAISIO.Access() << "]";
381 anInfo += aPtrStr.str().c_str();
383 if (!aShapePrs.IsNull()) {
384 const TopoDS_Shape& aShape = aShapePrs->Shape();
386 Events_Error::throwException("An empty AIS presentation");
388 anInfo += QString(", shape type: %1").arg(getShapeTypeInfo(aShape.ShapeType()));
390 TColStd_ListOfInteger aTColModes;
391 theContext->ActivatedModes(anAISIO, aTColModes);
392 TColStd_ListIteratorOfListOfInteger itr( aTColModes );
393 QIntList aModesActivatedForIO;
394 bool isDeactivated = false;
396 for (; itr.More(); itr.Next() ) {
397 Standard_Integer aMode = itr.Value();
398 aModes.append(getModeInfo(aMode));
399 //int aShapeMode = (aMode > 8)? aMode : AIS_Shape::SelectionType(aMode);
401 if (aModes.size() > 0)
402 anInfo += QString(", activated modes: %1").arg(aModes.join(", "));
406 QString aValue = QString("displayedIO[%1]").arg(anObjects.size());
407 if (anObjects.size() > 0)
408 aValue += QString(":\n %1").arg(anObjects.join("\n "));
412 QString activeOwners(Handle(AIS_InteractiveContext)& theContext, const bool theShapeInfoOnly = true)
414 if (theContext.IsNull())
416 Handle(AIS_LocalContext) aLContext = theContext->LocalContext();
417 TCollection_AsciiString aSelectionName = aLContext->SelectionName();
418 aLContext->UnhilightPicked(Standard_False);
420 NCollection_List<Handle(SelectBasics_EntityOwner)> anActiveOwners;
421 aLContext->MainSelector()->ActiveOwners(anActiveOwners);
422 NCollection_List<Handle(SelectBasics_EntityOwner)>::Iterator anOwnersIt (anActiveOwners);
423 Handle(SelectMgr_EntityOwner) anOwner;
424 QStringList anObjects;
425 for (; anOwnersIt.More(); anOwnersIt.Next()) {
426 anOwner = Handle(SelectMgr_EntityOwner)::DownCast (anOwnersIt.Value());
427 Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
428 if (theShapeInfoOnly && BROwnr.IsNull())
431 QString anInfo = "Owner";
432 std::ostringstream aPtrStr;
433 aPtrStr << "[" << anOwner.Access() << "]";
434 anInfo += aPtrStr.str().c_str();
436 Handle(AIS_InteractiveObject) aAISObj =
437 Handle(AIS_InteractiveObject)::DownCast(anOwner->Selectable());
438 if (!aAISObj.IsNull()) {
439 std::ostringstream aPtrStr;
440 aPtrStr << "[" << aAISObj.Access() << "]";
441 anInfo += QString(", selectable(IO): %1").arg(aPtrStr.str().c_str());
444 if (!BROwnr.IsNull() && BROwnr->HasShape()) {
445 const TopoDS_Shape& aShape = BROwnr->Shape();
447 Events_Error::throwException("An empty AIS presentation");
449 anInfo += QString(", shape type: %1").arg(getShapeTypeInfo(aShape.ShapeType()));
453 QString aValue = QString("activeOwners[%1]").arg(anObjects.size());
454 if (anObjects.size() > 0)
455 aValue += QString(":\n %1").arg(anObjects.join("\n "));
459 QString selectedOwners(Handle(AIS_InteractiveContext)& theContext, const bool theShapeInfoOnly = true)
461 QStringList anObjects;
462 if (theContext.IsNull())
465 QList<long> aSelectedIds; // Remember of selected address in order to avoid duplicates
466 for (theContext->InitSelected(); theContext->MoreSelected(); theContext->NextSelected()) {
467 Handle(SelectMgr_EntityOwner) anOwner = theContext->SelectedOwner();
468 Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
469 if (theShapeInfoOnly && BROwnr.IsNull())
472 if (aSelectedIds.contains((long)anOwner.Access()))
474 aSelectedIds.append((long)anOwner.Access());
476 QString anInfo = "Owner";
477 std::ostringstream aPtrStr;
478 aPtrStr << "[" << anOwner.Access() << "]";
479 anInfo += aPtrStr.str().c_str();
481 if (!BROwnr.IsNull() && BROwnr->HasShape()) {
482 const TopoDS_Shape& aShape = BROwnr->Shape();
483 anInfo += QString(", shape type = %1").arg(getShapeTypeInfo(aShape.ShapeType()));
487 QString aValue = QString("selectedOwners[%1]").arg(anObjects.size());
488 if (anObjects.size() > 0)
489 aValue += QString(":\n %1").arg(anObjects.join("\n "));
494 void selectionInfo(Handle(AIS_InteractiveContext)& theContext, const std::string& thePrefix)
496 #ifdef DEBUG_SELECTION_INFO
497 QString aValue = QString("\n\n\nDEBUG_SELECTION_INFO for '%1'\n%2\n%3\n%4")
498 .arg(thePrefix.c_str())
499 .arg(displayedInteractiveObjects(theContext))
500 .arg(activeOwners(theContext))
501 .arg(selectedOwners(theContext));
502 qDebug(aValue.toStdString().c_str());
506 typedef QMap<QString, TopAbs_ShapeEnum> ShapeTypes;
507 static ShapeTypes myShapeTypes;
509 TopAbs_ShapeEnum shapeType(const QString& theType)
511 if (myShapeTypes.count() == 0) {
512 myShapeTypes["compound"] = TopAbs_COMPOUND;
513 myShapeTypes["compounds"] = TopAbs_COMPOUND;
514 myShapeTypes["compsolid"] = TopAbs_COMPSOLID;
515 myShapeTypes["compsolids"] = TopAbs_COMPSOLID;
516 myShapeTypes["solid"] = TopAbs_SOLID;
517 myShapeTypes["solids"] = TopAbs_SOLID;
518 myShapeTypes["shell"] = TopAbs_SHELL;
519 myShapeTypes["shells"] = TopAbs_SHELL;
520 myShapeTypes["face"] = TopAbs_FACE;
521 myShapeTypes["faces"] = TopAbs_FACE;
522 myShapeTypes["wire"] = TopAbs_WIRE;
523 myShapeTypes["wires"] = TopAbs_WIRE;
524 myShapeTypes["edge"] = TopAbs_EDGE;
525 myShapeTypes["edges"] = TopAbs_EDGE;
526 myShapeTypes["vertex"] = TopAbs_VERTEX;
527 myShapeTypes["vertices"] = TopAbs_VERTEX;
528 myShapeTypes["objects"] = TopAbs_SHAPE;
530 QString aType = theType.toLower();
531 if(myShapeTypes.contains(aType))
532 return myShapeTypes[aType];
533 Events_Error::send("Shape type defined in XML is not implemented!");
537 void checkObjects(const QObjectPtrList& theObjects, bool& hasResult, bool& hasFeature,
538 bool& hasParameter, bool& hasCompositeOwner)
542 hasParameter = false;
543 hasCompositeOwner = false;
544 foreach(ObjectPtr aObj, theObjects) {
545 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
546 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
547 ResultParameterPtr aConstruction = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aResult);
549 hasResult |= (aResult.get() != NULL);
550 hasFeature |= (aFeature.get() != NULL);
551 hasParameter |= (aConstruction.get() != NULL);
553 hasCompositeOwner |= (ModelAPI_Tools::compositeOwner(aFeature) != NULL);
554 if (hasFeature && hasResult && hasParameter && hasCompositeOwner)
559 void setDefaultDeviationCoefficient(const TopoDS_Shape& theShape,
560 const Handle(Prs3d_Drawer)& theDrawer)
562 if (theShape.IsNull())
564 TopAbs_ShapeEnum aType = theShape.ShapeType();
565 if ((aType == TopAbs_EDGE) || (aType == TopAbs_WIRE))
566 theDrawer->SetDeviationCoefficient(1.e-4);
569 Quantity_Color color(const std::string& theSection,
570 const std::string& theName,
571 const std::string& theDefault)
573 std::vector<int> aColor = Config_PropManager::color(theSection, theName, theDefault);
574 return Quantity_Color(aColor[0] / 255., aColor[1] / 255., aColor[2] / 255., Quantity_TOC_RGB);
577 ObjectPtr getObject(const AttributePtr& theAttribute)
580 std::string anAttrType = theAttribute->attributeType();
581 if (anAttrType == ModelAPI_AttributeRefAttr::typeId()) {
582 AttributeRefAttrPtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
583 if (anAttr != NULL && anAttr->isObject())
584 anObject = anAttr->object();
586 if (anAttrType == ModelAPI_AttributeSelection::typeId()) {
587 AttributeSelectionPtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
589 anObject = anAttr->context();
591 if (anAttrType == ModelAPI_AttributeReference::typeId()) {
592 AttributeReferencePtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
593 if (anAttr.get() != NULL)
594 anObject = anAttr->value();
599 TopAbs_ShapeEnum getCompoundSubType(const TopoDS_Shape& theShape)
601 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
603 // for compounds check sub-shapes: it may be compound of needed type:
604 // Booleans may produce compounds of Solids
605 if (aShapeType == TopAbs_COMPOUND) {
606 for(TopoDS_Iterator aSubs(theShape); aSubs.More(); aSubs.Next()) {
607 if (!aSubs.Value().IsNull()) {
608 TopAbs_ShapeEnum aSubType = aSubs.Value().ShapeType();
609 if (aSubType == TopAbs_COMPOUND) { // compound of compound(s)
610 aShapeType = TopAbs_COMPOUND;
613 if (aShapeType == TopAbs_COMPOUND) {
614 aShapeType = aSubType;
615 } else if (aShapeType != aSubType) { // compound of shapes of different types
616 aShapeType = TopAbs_COMPOUND;
625 void getParameters(QStringList& theParameters)
627 theParameters.clear();
629 SessionPtr aSession = ModelAPI_Session::get();
630 std::list<DocumentPtr> aDocList;
631 DocumentPtr anActiveDocument = aSession->activeDocument();
632 DocumentPtr aRootDocument = aSession->moduleDocument();
633 aDocList.push_back(anActiveDocument);
634 if (anActiveDocument != aRootDocument) {
635 aDocList.push_back(aRootDocument);
637 std::string aGroupId = ModelAPI_ResultParameter::group();
638 for(std::list<DocumentPtr>::const_iterator it = aDocList.begin(); it != aDocList.end(); ++it) {
639 DocumentPtr aDocument = *it;
640 int aSize = aDocument->size(aGroupId);
641 for (int i = 0; i < aSize; i++) {
642 ObjectPtr anObject = aDocument->object(aGroupId, i);
643 std::string aParameterName = anObject->data()->name();
644 theParameters.append(aParameterName.c_str());
649 std::string findGreedAttribute(ModuleBase_IWorkshop* theWorkshop, const FeaturePtr& theFeature)
651 std::string anAttributeId;
653 std::string aXmlCfg, aDescription;
654 theWorkshop->module()->getXMLRepresentation(theFeature->getKind(), aXmlCfg, aDescription);
656 ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
657 std::string anAttributeTitle;
658 aFactory.getGreedAttribute(anAttributeId);
660 return anAttributeId;
663 bool hasObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
664 const std::shared_ptr<GeomAPI_Shape>& theShape,
665 ModuleBase_IWorkshop* theWorkshop,
666 const bool theTemporarily)
668 bool aHasObject = false;
669 if (!theAttribute.get())
672 std::string aType = theAttribute->attributeType();
673 if (aType == ModelAPI_AttributeReference::typeId()) {
674 AttributeReferencePtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
675 ObjectPtr aObject = aRef->value();
676 aHasObject = aObject && aObject->isSame(theObject);
677 //if (!(aObject && aObject->isSame(theObject))) {
678 // aRef->setValue(theObject);
680 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
681 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
683 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
684 if (anAttribute.get()) {
685 //aRefAttr->setAttr(anAttribute);
688 ObjectPtr aObject = aRefAttr->object();
689 aHasObject = aObject && aObject->isSame(theObject);
690 //if (!(aObject && aObject->isSame(theObject))) {
691 // aRefAttr->setObject(theObject);
694 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
695 /*AttributeSelectionPtr aSelectAttr =
696 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
697 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
698 if (aSelectAttr.get() != NULL) {
699 aSelectAttr->setValue(aResult, theShape, theTemporarily);
702 if (aType == ModelAPI_AttributeSelectionList::typeId()) {
703 AttributeSelectionListPtr aSelectionListAttr =
704 std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
705 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
706 aHasObject = aSelectionListAttr->isInList(aResult, theShape, theTemporarily);
707 //if (!theCheckIfAttributeHasObject || !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
708 // aSelectionListAttr->append(aResult, theShape, theTemporarily);
710 else if (aType == ModelAPI_AttributeRefList::typeId()) {
711 AttributeRefListPtr aRefListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
712 aHasObject = aRefListAttr->isInList(theObject);
713 //if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
714 // aRefListAttr->append(theObject);
716 else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
717 AttributeRefAttrListPtr aRefAttrListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
718 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
720 if (anAttribute.get()) {
721 aHasObject = aRefAttrListAttr->isInList(anAttribute);
722 //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
723 // aRefAttrListAttr->append(anAttribute);
726 aHasObject = aRefAttrListAttr->isInList(theObject);
727 //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
728 // aRefAttrListAttr->append(theObject);
734 void setObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
735 const GeomShapePtr& theShape, ModuleBase_IWorkshop* theWorkshop,
736 const bool theTemporarily, const bool theCheckIfAttributeHasObject)
738 if (!theAttribute.get())
741 std::string aType = theAttribute->attributeType();
742 if (aType == ModelAPI_AttributeReference::typeId()) {
743 AttributeReferencePtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
744 ObjectPtr aObject = aRef->value();
745 if (!(aObject && aObject->isSame(theObject))) {
746 aRef->setValue(theObject);
748 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
749 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
751 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
752 if (anAttribute.get())
753 aRefAttr->setAttr(anAttribute);
755 ObjectPtr aObject = aRefAttr->object();
756 if (!(aObject && aObject->isSame(theObject))) {
757 aRefAttr->setObject(theObject);
760 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
761 AttributeSelectionPtr aSelectAttr =
762 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
763 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
764 if (aSelectAttr.get() != NULL) {
765 aSelectAttr->setValue(aResult, theShape, theTemporarily);
768 if (aType == ModelAPI_AttributeSelectionList::typeId()) {
769 AttributeSelectionListPtr aSelectionListAttr =
770 std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
771 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
772 if (!theCheckIfAttributeHasObject || !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
773 aSelectionListAttr->append(aResult, theShape, theTemporarily);
775 else if (aType == ModelAPI_AttributeRefList::typeId()) {
776 AttributeRefListPtr aRefListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
777 if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
778 aRefListAttr->append(theObject);
780 else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
781 AttributeRefAttrListPtr aRefAttrListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
782 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
784 if (anAttribute.get()) {
785 if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
786 aRefAttrListAttr->append(anAttribute);
789 if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
790 aRefAttrListAttr->append(theObject);
795 GeomShapePtr getShape(const AttributePtr& theAttribute, ModuleBase_IWorkshop* theWorkshop)
798 if (!theAttribute.get())
801 std::string aType = theAttribute->attributeType();
802 if (aType == ModelAPI_AttributeReference::typeId()) {
803 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
804 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
805 if (aRefAttr.get() && !aRefAttr->isObject()) {
806 AttributePtr anAttribute = aRefAttr->attr();
807 aShape = theWorkshop->module()->findShape(anAttribute);
809 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
810 AttributeSelectionPtr aSelectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>
812 aShape = aSelectAttr->value();
817 void flushUpdated(ObjectPtr theObject)
819 blockUpdateViewer(true);
821 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
823 blockUpdateViewer(false);
826 void blockUpdateViewer(const bool theValue)
828 // the viewer update should be blocked in order to avoid the temporary feature content
829 // when the solver processes the feature, the redisplay message can be flushed
830 // what caused the display in the viewer preliminary states of object
831 // e.g. fillet feature, angle value change
832 std::shared_ptr<Events_Message> aMsg;
834 aMsg = std::shared_ptr<Events_Message>(
835 new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)));
838 // the viewer update should be unblocked
839 aMsg = std::shared_ptr<Events_Message>(
840 new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)));
842 Events_Loop::loop()->send(aMsg);
845 QString wrapTextByWords(const QString& theValue, QWidget* theWidget,
846 int theMaxLineInPixels)
848 static QFontMetrics tfm(theWidget ? theWidget->font() : QApplication::font());
849 static qreal phi = 2.618;
851 QRect aBounds = tfm.boundingRect(theValue);
852 if(aBounds.width() <= theMaxLineInPixels)
855 qreal s = aBounds.width() * aBounds.height();
856 qreal aGoldWidth = sqrt(s*phi);
858 QStringList aWords = theValue.split(" ", QString::SkipEmptyParts);
860 int n = aWords.count();
862 for (int i = 0; i < n; i++) {
863 QString aLineExt = aLine + " " + aWords[i];
864 qreal anWidthNonExt = tfm.boundingRect(aLine).width();
865 qreal anWidthExt = tfm.boundingRect(aLineExt).width();
866 qreal aDeltaNonExt = fabs(anWidthNonExt-aGoldWidth);
867 qreal aDeltaExt = fabs(anWidthExt-aGoldWidth);
868 if(aDeltaNonExt < aDeltaExt) {
870 aLines.append(aLine);
878 aLines.append(aLine);
880 QString aResult = aLines.join("\n");
884 //**************************************************************
885 void refsToFeatureInFeatureDocument(const ObjectPtr& theObject, std::set<FeaturePtr>& theRefFeatures)
887 FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
888 if (aFeature.get()) {
889 DocumentPtr aFeatureDoc = aFeature->document();
890 // 1. find references in the current document
891 aFeatureDoc->refsToFeature(aFeature, theRefFeatures, false);
896 //**************************************************************
897 bool isSubOfComposite(const ObjectPtr& theObject)
900 std::set<FeaturePtr> aRefFeatures;
901 refsToFeatureInFeatureDocument(theObject, aRefFeatures);
902 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
903 aLast = aRefFeatures.end();
904 for (; anIt != aLast && !isSub; anIt++) {
905 isSub = isSubOfComposite(theObject, *anIt);
910 //**************************************************************
911 bool isSubOfComposite(const ObjectPtr& theObject, const FeaturePtr& theFeature)
914 CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
915 if (aComposite.get()) {
916 isSub = aComposite->isSub(theObject);
917 // the recursive is possible, the parameters are sketch circle and extrusion cut. They are
918 // separated by composite sketch feature
920 int aNbSubs = aComposite->numberOfSubs();
921 for (int aSub = 0; aSub < aNbSubs && !isSub; aSub++) {
922 isSub = isSubOfComposite(theObject, aComposite->subFeature(aSub));
929 //**************************************************************
930 bool isFeatureOfResult(const FeaturePtr& theFeature, const std::string& theGroupOfResult)
932 bool isResult = false;
934 if (!theFeature->data()->isValid())
937 ResultPtr aFirstResult = theFeature->firstResult();
938 if (!aFirstResult.get())
941 return aFirstResult->groupName() == theGroupOfResult;
944 //**************************************************************
945 bool askToDelete(const std::set<FeaturePtr> theFeatures,
946 const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
948 std::set<FeaturePtr>& theReferencesToDelete)
950 std::set<FeaturePtr> aFeaturesRefsTo;
951 std::set<FeaturePtr> aFeaturesRefsToParameter;
952 std::set<FeaturePtr> aParameterFeatures;
953 std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
954 aLast = theFeatures.end();
955 // separate features to references to parameter features and references to others
956 for (; anIt != aLast; anIt++) {
957 FeaturePtr aFeature = *anIt;
958 if (theReferences.find(aFeature) == theReferences.end())
961 std::set<FeaturePtr> aRefFeatures;
962 std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
963 std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
964 for (; aRefIt != aRefLast; aRefIt++) {
965 FeaturePtr aRefFeature = *aRefIt;
966 if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
967 aRefFeatures.find(aRefFeature) == aRefFeatures.end()) // it is not added
968 aRefFeatures.insert(aRefFeature);
971 if (isFeatureOfResult(aFeature, ModelAPI_ResultParameter::group())) {
972 aFeaturesRefsToParameter.insert(aRefFeatures.begin(), aRefFeatures.end());
973 aParameterFeatures.insert(aFeature);
976 theReferencesToDelete.insert(aRefFeatures.begin(), aRefFeatures.end());
980 std::set<FeaturePtr> aFeaturesRefsToParameterOnly;
981 anIt = aFeaturesRefsToParameter.begin();
982 aLast = aFeaturesRefsToParameter.end();
983 // separate features to references to parameter features and references to others
984 QStringList aParamFeatureNames;
985 for (; anIt != aLast; anIt++) {
986 FeaturePtr aFeature = *anIt;
987 if (theReferencesToDelete.find(aFeature) == theReferencesToDelete.end()) {
988 aFeaturesRefsToParameterOnly.insert(aFeature);
989 aParamFeatureNames.append(aFeature->name().c_str());
992 aParamFeatureNames.sort();
993 QStringList aPartFeatureNames, anOtherFeatureNames;
994 anIt = theReferencesToDelete.begin();
995 aLast = theReferencesToDelete.end();
996 for (; anIt != aLast; anIt++) {
997 FeaturePtr aFeature = *anIt;
998 if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
999 aPartFeatureNames.append(aFeature->name().c_str());
1001 anOtherFeatureNames.append(aFeature->name().c_str());
1003 aPartFeatureNames.sort();
1004 anOtherFeatureNames.sort();
1006 bool aCanReplaceParameters = !aFeaturesRefsToParameterOnly.empty();
1008 QMessageBox aMessageBox(theParent);
1009 aMessageBox.setWindowTitle(QObject::tr("Delete features"));
1010 aMessageBox.setIcon(QMessageBox::Warning);
1011 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1012 aMessageBox.setDefaultButton(QMessageBox::No);
1015 QString aSep = ", ";
1016 if (!aPartFeatureNames.empty())
1017 aText += QString(QObject::tr("The following parts will be deleted: %1.\n")).arg(aPartFeatureNames.join(aSep));
1018 if (!anOtherFeatureNames.empty())
1019 aText += QString(QObject::tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n"))
1020 .arg(anOtherFeatureNames.join(aSep));
1021 if (!aParamFeatureNames.empty()) {
1022 aText += QString(QObject::tr("Selected parameters are used in the following features: %1.\nThese features will be deleted.\nOr parameters could be replaced by their values.\n"))
1023 .arg(aParamFeatureNames.join(aSep));
1024 QPushButton *aReplaceButton = aMessageBox.addButton(QObject::tr("Replace"), QMessageBox::ActionRole);
1027 if (!aText.isEmpty()) {
1028 aText += "Would you like to continue?";
1029 aMessageBox.setText(aText);
1031 QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1033 if (aButtonRole == QMessageBox::NoRole)
1036 if (aButtonRole == QMessageBox::ActionRole) {
1037 foreach (FeaturePtr aObj, aParameterFeatures)
1038 ModelAPI_ReplaceParameterMessage::send(aObj, 0);
1041 theReferencesToDelete.insert(aFeaturesRefsToParameterOnly.begin(), aFeaturesRefsToParameterOnly.end());
1046 //**************************************************************
1047 void convertToFeatures(const QObjectPtrList& theObjects, std::set<FeaturePtr>& theFeatures)
1049 QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1050 for(; anIt != aLast; anIt++) {
1051 ObjectPtr anObject = *anIt;
1052 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1053 // for parameter result, use the corresponded reature to be removed
1054 if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1055 aFeature = ModelAPI_Feature::feature(anObject);
1057 theFeatures.insert(aFeature);
1061 } // namespace ModuleBase_Tools