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 <ModelAPI_ResultConstruction.h>
25 #include <Events_Loop.h>
27 #include <ModelAPI_Data.h>
28 #include <ModelAPI_Result.h>
29 #include <ModelAPI_ResultCompSolid.h>
30 #include <ModelAPI_ResultParameter.h>
31 #include <ModelAPI_Tools.h>
32 #include <ModelAPI_Session.h>
33 #include <ModelAPI_Events.h>
35 #include <TopoDS_Iterator.hxx>
37 #include <GeomDataAPI_Point2D.h>
38 #include <GeomAPI_ShapeExplorer.h>
39 #include <Events_Error.h>
41 #include <Config_PropManager.h>
47 #include <QDoubleSpinBox>
48 #include <QGraphicsDropShadowEffect>
50 #include <QApplication>
51 #include <QMessageBox>
57 const double tolerance = 1e-7;
58 const double DEFAULT_DEVIATION_COEFFICIENT = 1.e-4;
60 //#define DEBUG_ACTIVATE_WINDOW
61 //#define DEBUG_SET_FOCUS
62 //#define DEBUG_SELECTION_INFO
64 #ifdef DEBUG_SELECTION_INFO
65 #include <ModuleBase_ISelection.h>
66 #include <ModuleBase_ViewerPrs.h>
68 #include <AIS_InteractiveContext.hxx>
69 #include <AIS_ListOfInteractive.hxx>
70 #include <AIS_ListIteratorOfListOfInteractive.hxx>
71 #include <AIS_Shape.hxx>
72 #include <TopoDS_Shape.hxx>
73 #include <AIS_LocalContext.hxx>
74 #include <NCollection_List.hxx>
75 #include <StdSelect_BRepOwner.hxx>
76 #include <TColStd_ListOfInteger.hxx>
77 #include <TColStd_ListIteratorOfListOfInteger.hxx>
80 namespace ModuleBase_Tools {
82 //******************************************************************
84 //******************************************************************
86 void adjustMargins(QWidget* theWidget)
90 adjustMargins(theWidget->layout());
93 void adjustMargins(QLayout* theLayout)
97 theLayout->setContentsMargins(2, 5, 2, 5);
98 theLayout->setSpacing(4);
101 void zeroMargins(QWidget* theWidget)
105 zeroMargins(theWidget->layout());
108 void zeroMargins(QLayout* theLayout)
112 theLayout->setContentsMargins(0, 0, 0, 0);
113 theLayout->setSpacing(5);
116 void activateWindow(QWidget* theWidget, const QString& theInfo)
118 theWidget->activateWindow();
120 #ifdef DEBUG_ACTIVATE_WINDOW
121 qDebug(QString("activateWindow: %1").arg(theInfo).toStdString().c_str());
125 void setFocus(QWidget* theWidget, const QString& theInfo)
127 theWidget->setFocus();
129 #ifdef DEBUG_SET_FOCUS
130 qDebug(QString("setFocus: %1").arg(theInfo).toStdString().c_str());
134 void setShadowEffect(QWidget* theWidget, const bool isSetEffect)
137 QGraphicsDropShadowEffect* aGlowEffect = new QGraphicsDropShadowEffect();
138 aGlowEffect->setOffset(.0);
139 aGlowEffect->setBlurRadius(10.0);
140 aGlowEffect->setColor(QColor(0, 170, 255)); // Light-blue color, #00AAFF
141 theWidget->setGraphicsEffect(aGlowEffect);
144 QGraphicsEffect* anEffect = theWidget->graphicsEffect();
146 anEffect->deleteLater();
147 theWidget->setGraphicsEffect(NULL);
151 QPixmap composite(const QString& theAdditionalIcon, const QString& theIcon)
153 QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
154 QImage anAditional(theAdditionalIcon);
159 int anAddWidth = anAditional.width();
160 int anAddHeight = anAditional.height();
162 int aWidth = anIcon.width();
163 int aHeight = anIcon.height();
165 int aStartWidthPos = aWidth - anAddWidth - 1;
166 int aStartHeightPos = aHeight - anAddHeight - 1;
168 for (int i = 0; i < anAddWidth && i + aStartWidthPos < aWidth; i++)
170 for (int j = 0; j < anAddHeight && j + aStartHeightPos < aHeight; j++)
172 if (qAlpha(anAditional.pixel(i, j)) > 0)
173 anIcon.setPixel(i + aStartWidthPos, j + aStartHeightPos, anAditional.pixel(i, j));
176 return QPixmap::fromImage(anIcon);
179 QPixmap lighter(const QString& theIcon, const int theLighterValue)
181 QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
185 QImage aResult = ModuleBase_IconFactory::loadImage(theIcon);
186 for (int i = 0; i < anIcon.width(); i++)
188 for (int j = 0; j < anIcon.height(); j++)
190 QRgb anRgb = anIcon.pixel(i, j);
191 QColor aPixelColor(qRed(anRgb), qGreen(anRgb), qBlue(anRgb),
192 qAlpha(aResult.pixel(i, j)));
194 QColor aLighterColor = aPixelColor.lighter(theLighterValue);
195 aResult.setPixel(i, j, qRgba(aLighterColor.red(), aLighterColor.green(),
196 aLighterColor.blue(), aLighterColor.alpha()));
199 return QPixmap::fromImage(aResult);
202 void setSpinText(ModuleBase_ParamSpinBox* theSpin, const QString& theText)
204 if (theSpin->text() == theText)
206 // In order to avoid extra text setting because it will
207 // reset cursor position in control
208 bool isBlocked = theSpin->blockSignals(true);
209 theSpin->setText(theText);
210 theSpin->blockSignals(isBlocked);
213 void setSpinValue(QDoubleSpinBox* theSpin, double theValue)
215 if (fabs(theSpin->value() - theValue) < tolerance)
217 bool isBlocked = theSpin->blockSignals(true);
218 theSpin->setValue(theValue);
219 theSpin->blockSignals(isBlocked);
222 void setSpinValue(ModuleBase_ParamSpinBox* theSpin, double theValue)
224 if (fabs(theSpin->value() - theValue) < tolerance)
226 bool isBlocked = theSpin->blockSignals(true);
227 theSpin->setValue(theValue);
228 theSpin->blockSignals(isBlocked);
231 void setSpinText(ModuleBase_ParamIntSpinBox* theSpin, const QString& theText)
233 // In order to avoid extra text setting because it will
234 // reset cursor position in control
235 if (theSpin->text() == theText)
237 bool isBlocked = theSpin->blockSignals(true);
238 theSpin->setText(theText);
239 theSpin->blockSignals(isBlocked);
242 void setSpinValue(ModuleBase_ParamIntSpinBox* theSpin, int theValue)
244 if (theSpin->value() == theValue)
246 bool isBlocked = theSpin->blockSignals(true);
247 theSpin->setValue(theValue);
248 theSpin->blockSignals(isBlocked);
251 QAction* createAction(const QIcon& theIcon, const QString& theText,
252 QObject* theParent, const QObject* theReceiver,
253 const char* theMember, const QString& theToolTip,
254 const QString& theStatusTip)
256 QAction* anAction = new QAction(theIcon, theText, theParent);
257 anAction->setToolTip(theToolTip.isEmpty() ? theText : theToolTip);
258 anAction->setStatusTip(!theStatusTip.isEmpty() ? theStatusTip :
259 (!theToolTip.isEmpty() ? theToolTip : theText));
261 QObject::connect(anAction, SIGNAL(triggered(bool)), theReceiver, theMember);
266 QString objectInfo(const ObjectPtr& theObj, const bool isUseAttributesInfo)
268 QString aFeatureStr = "feature";
272 std::ostringstream aPtrStr;
273 aPtrStr << "[" << theObj.get() << "]";
275 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theObj);
276 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
278 aFeatureStr.append(QString("(result%1)").arg(aPtrStr.str().c_str()).toStdString() .c_str());
279 if (aRes->isDisabled())
280 aFeatureStr.append("[disabled]");
281 if (aRes->isConcealed())
282 aFeatureStr.append("[concealed]");
283 if (ModelAPI_Tools::hasSubResults(aRes))
284 aFeatureStr.append("[hasSubResults]");
286 aFeature = ModelAPI_Feature::feature(aRes);
289 aFeatureStr.append(aPtrStr.str().c_str());
291 if (aFeature.get()) {
292 aFeatureStr.append(QString(": %1").arg(aFeature->getKind().c_str()).toStdString().c_str());
293 if (aFeature->data()->isValid()) {
294 aFeatureStr.append(QString(", name=%1").arg(theObj->data()->name().c_str()).toStdString()
297 if (isUseAttributesInfo) {
298 std::list<AttributePtr> anAttrs = aFeature->data()->attributes("");
299 std::list<AttributePtr>::const_iterator anIt = anAttrs.begin(), aLast = anAttrs.end();
301 for(; anIt != aLast; anIt++) {
302 AttributePtr anAttr = *anIt;
303 QString aValue = "not defined";
304 std::string aType = anAttr->attributeType();
305 if (aType == GeomDataAPI_Point2D::typeId()) {
306 std::shared_ptr<GeomDataAPI_Point2D> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
309 aValue = QString("(%1, %2)").arg(aPoint->x()).arg(aPoint->y());
311 else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
314 aValues.push_back(QString("%1: %2").arg(anAttr->id().c_str()).arg(aValue).toStdString().c_str());
316 if (!aValues.empty())
317 aFeatureStr.append(QString(", attributes: %1").arg(aValues.join(", ").toStdString().c_str()));
324 #ifdef DEBUG_SELECTION_INFO
325 QString getShapeTypeInfo(const int theType)
327 QString anInfo = "Undefined";
329 case TopAbs_COMPOUND: anInfo = "compound"; break;
330 case TopAbs_COMPSOLID: anInfo = "compsolid"; break;
331 case TopAbs_SOLID: anInfo = "solid"; break;
332 case TopAbs_SHELL: anInfo = "shell"; break;
333 case TopAbs_FACE: anInfo = "face"; break;
334 case TopAbs_WIRE: anInfo = "wire"; break;
335 case TopAbs_EDGE: anInfo = "edge"; break;
336 case TopAbs_VERTEX: anInfo = "vertex"; break;
337 case TopAbs_SHAPE: anInfo = "shape"; break;
343 QString getModeInfo(const int theMode)
345 QString anInfo = "Undefined";
347 case 0: anInfo = "SHAPE(0)"; break;
348 case 1: anInfo = "VERTEX(1)"; break;
349 case 2: anInfo = "EDGE(2)"; break;
350 case 3: anInfo = "WIRE(3)"; break;
351 case 4: anInfo = "FACE(4)"; break;
352 case 5: anInfo = "SHELL(5)"; break;
353 case 6: anInfo = "SOLID(6)"; break;
354 case 7: anInfo = "COMPSOLID(7)"; break;
355 case 8: anInfo = "COMPOUND(8)"; break;
356 case 100: anInfo = "Sel_Mode_First(100)"; break; //SketcherPrs_Tools
357 case 101: anInfo = "Sel_Constraint(101)"; break;
358 case 102: anInfo = "Sel_Dimension_All(102)"; break;
359 case 103: anInfo = "Sel_Dimension_Line(103)"; break;
360 case 104: anInfo = "Sel_Dimension_Text(104)"; break;
366 QString displayedInteractiveObjects(Handle(AIS_InteractiveContext)& theContext,
367 const bool theShapeInfoOnly = true)
369 if (theContext.IsNull())
371 AIS_ListOfInteractive aListOfIO;
372 theContext->DisplayedObjects(aListOfIO, false);
373 QStringList anObjects;
374 AIS_ListIteratorOfListOfInteractive aIt;
375 for (aIt.Initialize(aListOfIO); aIt.More(); aIt.Next()) {
376 Handle(AIS_InteractiveObject) anAISIO = aIt.Value();
377 Handle(AIS_Shape) aShapePrs = Handle(AIS_Shape)::DownCast(anAISIO);
378 if (theShapeInfoOnly && aShapePrs.IsNull())
381 QString anInfo = "IO";
382 std::ostringstream aPtrStr;
383 aPtrStr << "[" << anAISIO.Access() << "]";
384 anInfo += aPtrStr.str().c_str();
386 if (!aShapePrs.IsNull()) {
387 const TopoDS_Shape& aShape = aShapePrs->Shape();
389 Events_Error::throwException("An empty AIS presentation");
391 anInfo += QString(", shape type: %1").arg(getShapeTypeInfo(aShape.ShapeType()));
393 TColStd_ListOfInteger aTColModes;
394 theContext->ActivatedModes(anAISIO, aTColModes);
395 TColStd_ListIteratorOfListOfInteger itr( aTColModes );
396 QIntList aModesActivatedForIO;
397 bool isDeactivated = false;
399 for (; itr.More(); itr.Next() ) {
400 Standard_Integer aMode = itr.Value();
401 aModes.append(getModeInfo(aMode));
402 //int aShapeMode = (aMode > 8)? aMode : AIS_Shape::SelectionType(aMode);
404 if (aModes.size() > 0)
405 anInfo += QString(", activated modes: %1").arg(aModes.join(", "));
409 QString aValue = QString("displayedIO[%1]").arg(anObjects.size());
410 if (anObjects.size() > 0)
411 aValue += QString(":\n %1").arg(anObjects.join("\n "));
415 QString activeOwners(Handle(AIS_InteractiveContext)& theContext, const bool theShapeInfoOnly = true)
417 if (theContext.IsNull())
419 Handle(AIS_LocalContext) aLContext = theContext->LocalContext();
420 TCollection_AsciiString aSelectionName = aLContext->SelectionName();
421 aLContext->UnhilightPicked(Standard_False);
423 NCollection_List<Handle(SelectBasics_EntityOwner)> anActiveOwners;
424 aLContext->MainSelector()->ActiveOwners(anActiveOwners);
425 NCollection_List<Handle(SelectBasics_EntityOwner)>::Iterator anOwnersIt (anActiveOwners);
426 Handle(SelectMgr_EntityOwner) anOwner;
427 QStringList anObjects;
428 for (; anOwnersIt.More(); anOwnersIt.Next()) {
429 anOwner = Handle(SelectMgr_EntityOwner)::DownCast (anOwnersIt.Value());
430 Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
431 if (theShapeInfoOnly && BROwnr.IsNull())
434 QString anInfo = "Owner";
435 std::ostringstream aPtrStr;
436 aPtrStr << "[" << anOwner.Access() << "]";
437 anInfo += aPtrStr.str().c_str();
439 Handle(AIS_InteractiveObject) aAISObj =
440 Handle(AIS_InteractiveObject)::DownCast(anOwner->Selectable());
441 if (!aAISObj.IsNull()) {
442 std::ostringstream aPtrStr;
443 aPtrStr << "[" << aAISObj.Access() << "]";
444 anInfo += QString(", selectable(IO): %1").arg(aPtrStr.str().c_str());
447 if (!BROwnr.IsNull() && BROwnr->HasShape()) {
448 const TopoDS_Shape& aShape = BROwnr->Shape();
450 Events_Error::throwException("An empty AIS presentation");
452 anInfo += QString(", shape type: %1").arg(getShapeTypeInfo(aShape.ShapeType()));
456 QString aValue = QString("activeOwners[%1]").arg(anObjects.size());
457 if (anObjects.size() > 0)
458 aValue += QString(":\n %1").arg(anObjects.join("\n "));
462 QString selectedOwners(Handle(AIS_InteractiveContext)& theContext, const bool theShapeInfoOnly = true)
464 QStringList anObjects;
465 if (theContext.IsNull())
468 QList<long> aSelectedIds; // Remember of selected address in order to avoid duplicates
469 for (theContext->InitSelected(); theContext->MoreSelected(); theContext->NextSelected()) {
470 Handle(SelectMgr_EntityOwner) anOwner = theContext->SelectedOwner();
471 Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
472 if (theShapeInfoOnly && BROwnr.IsNull())
475 if (aSelectedIds.contains((long)anOwner.Access()))
477 aSelectedIds.append((long)anOwner.Access());
479 QString anInfo = "Owner";
480 std::ostringstream aPtrStr;
481 aPtrStr << "[" << anOwner.Access() << "]";
482 anInfo += aPtrStr.str().c_str();
484 if (!BROwnr.IsNull() && BROwnr->HasShape()) {
485 const TopoDS_Shape& aShape = BROwnr->Shape();
486 anInfo += QString(", shape type = %1").arg(getShapeTypeInfo(aShape.ShapeType()));
490 QString aValue = QString("selectedOwners[%1]").arg(anObjects.size());
491 if (anObjects.size() > 0)
492 aValue += QString(":\n %1").arg(anObjects.join("\n "));
497 void selectionInfo(Handle(AIS_InteractiveContext)& theContext, const std::string& thePrefix)
499 #ifdef DEBUG_SELECTION_INFO
500 QString aValue = QString("\n\n\nDEBUG_SELECTION_INFO for '%1'\n%2\n%3\n%4")
501 .arg(thePrefix.c_str())
502 .arg(displayedInteractiveObjects(theContext))
503 .arg(activeOwners(theContext))
504 .arg(selectedOwners(theContext));
505 qDebug(aValue.toStdString().c_str());
509 typedef QMap<QString, TopAbs_ShapeEnum> ShapeTypes;
510 static ShapeTypes myShapeTypes;
512 TopAbs_ShapeEnum shapeType(const QString& theType)
514 if (myShapeTypes.count() == 0) {
515 myShapeTypes["compound"] = TopAbs_COMPOUND;
516 myShapeTypes["compounds"] = TopAbs_COMPOUND;
517 myShapeTypes["compsolid"] = TopAbs_COMPSOLID;
518 myShapeTypes["compsolids"] = TopAbs_COMPSOLID;
519 myShapeTypes["solid"] = TopAbs_SOLID;
520 myShapeTypes["solids"] = TopAbs_SOLID;
521 myShapeTypes["shell"] = TopAbs_SHELL;
522 myShapeTypes["shells"] = TopAbs_SHELL;
523 myShapeTypes["face"] = TopAbs_FACE;
524 myShapeTypes["faces"] = TopAbs_FACE;
525 myShapeTypes["wire"] = TopAbs_WIRE;
526 myShapeTypes["wires"] = TopAbs_WIRE;
527 myShapeTypes["edge"] = TopAbs_EDGE;
528 myShapeTypes["edges"] = TopAbs_EDGE;
529 myShapeTypes["vertex"] = TopAbs_VERTEX;
530 myShapeTypes["vertices"] = TopAbs_VERTEX;
531 myShapeTypes["objects"] = TopAbs_SHAPE;
533 QString aType = theType.toLower();
534 if(myShapeTypes.contains(aType))
535 return myShapeTypes[aType];
536 Events_Error::send("Shape type defined in XML is not implemented!");
540 void checkObjects(const QObjectPtrList& theObjects, bool& hasResult, bool& hasFeature,
541 bool& hasParameter, bool& hasCompositeOwner)
545 hasParameter = false;
546 hasCompositeOwner = false;
547 foreach(ObjectPtr aObj, theObjects) {
548 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
549 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
550 ResultParameterPtr aConstruction = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aResult);
552 hasResult |= (aResult.get() != NULL);
553 hasFeature |= (aFeature.get() != NULL);
554 hasParameter |= (aConstruction.get() != NULL);
556 hasCompositeOwner |= (ModelAPI_Tools::compositeOwner(aFeature) != NULL);
557 if (hasFeature && hasResult && hasParameter && hasCompositeOwner)
562 bool setDefaultDeviationCoefficient(std::shared_ptr<GeomAPI_Shape> theGeomShape)
564 if (!theGeomShape.get())
566 // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
567 // correction of deviation for them should not influence to the application performance
568 GeomAPI_ShapeExplorer anExp(theGeomShape, GeomAPI_Shape::FACE);
569 bool anEmpty = anExp.empty();
570 return !anExp.more();
573 void setDefaultDeviationCoefficient(const std::shared_ptr<ModelAPI_Result>& theResult,
574 const Handle(Prs3d_Drawer)& theDrawer)
576 if (!theResult.get())
578 bool aUseDeviation = false;
580 std::string aResultGroup = theResult->groupName();
581 if (aResultGroup == ModelAPI_ResultConstruction::group())
582 aUseDeviation = true;
583 else if (aResultGroup == ModelAPI_ResultBody::group()) {
584 GeomShapePtr aGeomShape = theResult->shape();
585 if (aGeomShape.get())
586 aUseDeviation = setDefaultDeviationCoefficient(aGeomShape);
589 theDrawer->SetDeviationCoefficient(DEFAULT_DEVIATION_COEFFICIENT);
592 void setDefaultDeviationCoefficient(const TopoDS_Shape& theShape,
593 const Handle(Prs3d_Drawer)& theDrawer)
595 if (theShape.IsNull())
598 std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape());
599 aGeomShape->setImpl(new TopoDS_Shape(theShape));
600 if (setDefaultDeviationCoefficient(aGeomShape))
601 theDrawer->SetDeviationCoefficient(DEFAULT_DEVIATION_COEFFICIENT);
604 Quantity_Color color(const std::string& theSection,
605 const std::string& theName,
606 const std::string& theDefault)
608 std::vector<int> aColor = Config_PropManager::color(theSection, theName, theDefault);
609 return Quantity_Color(aColor[0] / 255., aColor[1] / 255., aColor[2] / 255., Quantity_TOC_RGB);
612 ObjectPtr getObject(const AttributePtr& theAttribute)
615 std::string anAttrType = theAttribute->attributeType();
616 if (anAttrType == ModelAPI_AttributeRefAttr::typeId()) {
617 AttributeRefAttrPtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
618 if (anAttr != NULL && anAttr->isObject())
619 anObject = anAttr->object();
621 if (anAttrType == ModelAPI_AttributeSelection::typeId()) {
622 AttributeSelectionPtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
624 anObject = anAttr->context();
626 if (anAttrType == ModelAPI_AttributeReference::typeId()) {
627 AttributeReferencePtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
628 if (anAttr.get() != NULL)
629 anObject = anAttr->value();
634 TopAbs_ShapeEnum getCompoundSubType(const TopoDS_Shape& theShape)
636 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
638 // for compounds check sub-shapes: it may be compound of needed type:
639 // Booleans may produce compounds of Solids
640 if (aShapeType == TopAbs_COMPOUND) {
641 for(TopoDS_Iterator aSubs(theShape); aSubs.More(); aSubs.Next()) {
642 if (!aSubs.Value().IsNull()) {
643 TopAbs_ShapeEnum aSubType = aSubs.Value().ShapeType();
644 if (aSubType == TopAbs_COMPOUND) { // compound of compound(s)
645 aShapeType = TopAbs_COMPOUND;
648 if (aShapeType == TopAbs_COMPOUND) {
649 aShapeType = aSubType;
650 } else if (aShapeType != aSubType) { // compound of shapes of different types
651 aShapeType = TopAbs_COMPOUND;
660 void getParameters(QStringList& theParameters)
662 theParameters.clear();
664 SessionPtr aSession = ModelAPI_Session::get();
665 std::list<DocumentPtr> aDocList;
666 DocumentPtr anActiveDocument = aSession->activeDocument();
667 DocumentPtr aRootDocument = aSession->moduleDocument();
668 aDocList.push_back(anActiveDocument);
669 if (anActiveDocument != aRootDocument) {
670 aDocList.push_back(aRootDocument);
672 std::string aGroupId = ModelAPI_ResultParameter::group();
673 for(std::list<DocumentPtr>::const_iterator it = aDocList.begin(); it != aDocList.end(); ++it) {
674 DocumentPtr aDocument = *it;
675 int aSize = aDocument->size(aGroupId);
676 for (int i = 0; i < aSize; i++) {
677 ObjectPtr anObject = aDocument->object(aGroupId, i);
678 std::string aParameterName = anObject->data()->name();
679 theParameters.append(aParameterName.c_str());
684 std::string findGreedAttribute(ModuleBase_IWorkshop* theWorkshop, const FeaturePtr& theFeature)
686 std::string anAttributeId;
688 std::string aXmlCfg, aDescription;
689 theWorkshop->module()->getXMLRepresentation(theFeature->getKind(), aXmlCfg, aDescription);
691 ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
692 std::string anAttributeTitle;
693 aFactory.getGreedAttribute(anAttributeId);
695 return anAttributeId;
698 bool hasObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
699 const std::shared_ptr<GeomAPI_Shape>& theShape,
700 ModuleBase_IWorkshop* theWorkshop,
701 const bool theTemporarily)
703 bool aHasObject = false;
704 if (!theAttribute.get())
707 std::string aType = theAttribute->attributeType();
708 if (aType == ModelAPI_AttributeReference::typeId()) {
709 AttributeReferencePtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
710 ObjectPtr aObject = aRef->value();
711 aHasObject = aObject && aObject->isSame(theObject);
712 //if (!(aObject && aObject->isSame(theObject))) {
713 // aRef->setValue(theObject);
715 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
716 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
718 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
719 if (anAttribute.get()) {
720 //aRefAttr->setAttr(anAttribute);
723 ObjectPtr aObject = aRefAttr->object();
724 aHasObject = aObject && aObject->isSame(theObject);
725 //if (!(aObject && aObject->isSame(theObject))) {
726 // aRefAttr->setObject(theObject);
729 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
730 /*AttributeSelectionPtr aSelectAttr =
731 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
732 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
733 if (aSelectAttr.get() != NULL) {
734 aSelectAttr->setValue(aResult, theShape, theTemporarily);
737 if (aType == ModelAPI_AttributeSelectionList::typeId()) {
738 AttributeSelectionListPtr aSelectionListAttr =
739 std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
740 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
741 aHasObject = aSelectionListAttr->isInList(aResult, theShape, theTemporarily);
742 //if (!theCheckIfAttributeHasObject || !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
743 // aSelectionListAttr->append(aResult, theShape, theTemporarily);
745 else if (aType == ModelAPI_AttributeRefList::typeId()) {
746 AttributeRefListPtr aRefListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
747 aHasObject = aRefListAttr->isInList(theObject);
748 //if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
749 // aRefListAttr->append(theObject);
751 else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
752 AttributeRefAttrListPtr aRefAttrListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
753 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
755 if (anAttribute.get()) {
756 aHasObject = aRefAttrListAttr->isInList(anAttribute);
757 //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
758 // aRefAttrListAttr->append(anAttribute);
761 aHasObject = aRefAttrListAttr->isInList(theObject);
762 //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
763 // aRefAttrListAttr->append(theObject);
769 void setObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
770 const GeomShapePtr& theShape, ModuleBase_IWorkshop* theWorkshop,
771 const bool theTemporarily, const bool theCheckIfAttributeHasObject)
773 if (!theAttribute.get())
776 std::string aType = theAttribute->attributeType();
777 if (aType == ModelAPI_AttributeReference::typeId()) {
778 AttributeReferencePtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
779 ObjectPtr aObject = aRef->value();
780 if (!(aObject && aObject->isSame(theObject))) {
781 aRef->setValue(theObject);
783 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
784 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
786 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
787 if (anAttribute.get())
788 aRefAttr->setAttr(anAttribute);
790 ObjectPtr aObject = aRefAttr->object();
791 if (!(aObject && aObject->isSame(theObject))) {
792 aRefAttr->setObject(theObject);
795 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
796 AttributeSelectionPtr aSelectAttr =
797 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
798 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
799 if (aSelectAttr.get() != NULL) {
800 aSelectAttr->setValue(aResult, theShape, theTemporarily);
803 if (aType == ModelAPI_AttributeSelectionList::typeId()) {
804 AttributeSelectionListPtr aSelectionListAttr =
805 std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
806 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
807 if (!theCheckIfAttributeHasObject || !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
808 aSelectionListAttr->append(aResult, theShape, theTemporarily);
810 else if (aType == ModelAPI_AttributeRefList::typeId()) {
811 AttributeRefListPtr aRefListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
812 if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
813 aRefListAttr->append(theObject);
815 else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
816 AttributeRefAttrListPtr aRefAttrListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
817 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
819 if (anAttribute.get()) {
820 if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
821 aRefAttrListAttr->append(anAttribute);
824 if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
825 aRefAttrListAttr->append(theObject);
830 GeomShapePtr getShape(const AttributePtr& theAttribute, ModuleBase_IWorkshop* theWorkshop)
833 if (!theAttribute.get())
836 std::string aType = theAttribute->attributeType();
837 if (aType == ModelAPI_AttributeReference::typeId()) {
838 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
839 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
840 if (aRefAttr.get() && !aRefAttr->isObject()) {
841 AttributePtr anAttribute = aRefAttr->attr();
842 aShape = theWorkshop->module()->findShape(anAttribute);
844 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
845 AttributeSelectionPtr aSelectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>
847 aShape = aSelectAttr->value();
852 void flushUpdated(ObjectPtr theObject)
854 blockUpdateViewer(true);
856 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
858 blockUpdateViewer(false);
861 void blockUpdateViewer(const bool theValue)
863 // the viewer update should be blocked in order to avoid the temporary feature content
864 // when the solver processes the feature, the redisplay message can be flushed
865 // what caused the display in the viewer preliminary states of object
866 // e.g. fillet feature, angle value change
867 std::shared_ptr<Events_Message> aMsg;
869 aMsg = std::shared_ptr<Events_Message>(
870 new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)));
873 // the viewer update should be unblocked
874 aMsg = std::shared_ptr<Events_Message>(
875 new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)));
877 Events_Loop::loop()->send(aMsg);
880 QString wrapTextByWords(const QString& theValue, QWidget* theWidget,
881 int theMaxLineInPixels)
883 static QFontMetrics tfm(theWidget ? theWidget->font() : QApplication::font());
884 static qreal phi = 2.618;
886 QRect aBounds = tfm.boundingRect(theValue);
887 if(aBounds.width() <= theMaxLineInPixels)
890 qreal s = aBounds.width() * aBounds.height();
891 qreal aGoldWidth = sqrt(s*phi);
893 QStringList aWords = theValue.split(" ", QString::SkipEmptyParts);
895 int n = aWords.count();
897 for (int i = 0; i < n; i++) {
898 QString aLineExt = aLine + " " + aWords[i];
899 qreal anWidthNonExt = tfm.boundingRect(aLine).width();
900 qreal anWidthExt = tfm.boundingRect(aLineExt).width();
901 qreal aDeltaNonExt = fabs(anWidthNonExt-aGoldWidth);
902 qreal aDeltaExt = fabs(anWidthExt-aGoldWidth);
903 if(aDeltaNonExt < aDeltaExt) {
905 aLines.append(aLine);
913 aLines.append(aLine);
915 QString aResult = aLines.join("\n");
919 //**************************************************************
920 void refsToFeatureInFeatureDocument(const ObjectPtr& theObject, std::set<FeaturePtr>& theRefFeatures)
922 FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
923 if (aFeature.get()) {
924 DocumentPtr aFeatureDoc = aFeature->document();
925 // 1. find references in the current document
926 aFeatureDoc->refsToFeature(aFeature, theRefFeatures, false);
931 //**************************************************************
932 bool isSubOfComposite(const ObjectPtr& theObject)
935 std::set<FeaturePtr> aRefFeatures;
936 refsToFeatureInFeatureDocument(theObject, aRefFeatures);
937 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
938 aLast = aRefFeatures.end();
939 for (; anIt != aLast && !isSub; anIt++) {
940 isSub = isSubOfComposite(theObject, *anIt);
945 //**************************************************************
946 bool isSubOfComposite(const ObjectPtr& theObject, const FeaturePtr& theFeature)
949 CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
950 if (aComposite.get()) {
951 isSub = aComposite->isSub(theObject);
952 // the recursive is possible, the parameters are sketch circle and extrusion cut. They are
953 // separated by composite sketch feature
955 int aNbSubs = aComposite->numberOfSubs();
956 for (int aSub = 0; aSub < aNbSubs && !isSub; aSub++) {
957 isSub = isSubOfComposite(theObject, aComposite->subFeature(aSub));
964 //**************************************************************
965 bool isFeatureOfResult(const FeaturePtr& theFeature, const std::string& theGroupOfResult)
967 bool isResult = false;
969 if (!theFeature->data()->isValid())
972 ResultPtr aFirstResult = theFeature->firstResult();
973 if (!aFirstResult.get())
976 return aFirstResult->groupName() == theGroupOfResult;
979 //**************************************************************
980 bool askToDelete(const std::set<FeaturePtr> theFeatures,
981 const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
983 std::set<FeaturePtr>& theReferencesToDelete)
985 std::set<FeaturePtr> aFeaturesRefsTo;
986 std::set<FeaturePtr> aFeaturesRefsToParameter;
987 std::set<FeaturePtr> aParameterFeatures;
988 std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
989 aLast = theFeatures.end();
990 // separate features to references to parameter features and references to others
991 for (; anIt != aLast; anIt++) {
992 FeaturePtr aFeature = *anIt;
993 if (theReferences.find(aFeature) == theReferences.end())
996 std::set<FeaturePtr> aRefFeatures;
997 std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
998 std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
999 for (; aRefIt != aRefLast; aRefIt++) {
1000 FeaturePtr aRefFeature = *aRefIt;
1001 if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
1002 aRefFeatures.find(aRefFeature) == aRefFeatures.end()) // it is not added
1003 aRefFeatures.insert(aRefFeature);
1006 if (isFeatureOfResult(aFeature, ModelAPI_ResultParameter::group())) {
1007 aFeaturesRefsToParameter.insert(aRefFeatures.begin(), aRefFeatures.end());
1008 aParameterFeatures.insert(aFeature);
1011 theReferencesToDelete.insert(aRefFeatures.begin(), aRefFeatures.end());
1015 std::set<FeaturePtr> aFeaturesRefsToParameterOnly;
1016 anIt = aFeaturesRefsToParameter.begin();
1017 aLast = aFeaturesRefsToParameter.end();
1018 // separate features to references to parameter features and references to others
1019 QStringList aParamFeatureNames;
1020 for (; anIt != aLast; anIt++) {
1021 FeaturePtr aFeature = *anIt;
1022 if (theReferencesToDelete.find(aFeature) == theReferencesToDelete.end()) {
1023 aFeaturesRefsToParameterOnly.insert(aFeature);
1024 aParamFeatureNames.append(aFeature->name().c_str());
1027 aParamFeatureNames.sort();
1028 QStringList aPartFeatureNames, anOtherFeatureNames;
1029 anIt = theReferencesToDelete.begin();
1030 aLast = theReferencesToDelete.end();
1031 for (; anIt != aLast; anIt++) {
1032 FeaturePtr aFeature = *anIt;
1033 if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
1034 aPartFeatureNames.append(aFeature->name().c_str());
1036 anOtherFeatureNames.append(aFeature->name().c_str());
1038 aPartFeatureNames.sort();
1039 anOtherFeatureNames.sort();
1041 bool aCanReplaceParameters = !aFeaturesRefsToParameterOnly.empty();
1043 QMessageBox aMessageBox(theParent);
1044 aMessageBox.setWindowTitle(QObject::tr("Delete features"));
1045 aMessageBox.setIcon(QMessageBox::Warning);
1046 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1047 aMessageBox.setDefaultButton(QMessageBox::No);
1050 QString aSep = ", ";
1051 if (!aPartFeatureNames.empty())
1052 aText += QString(QObject::tr("The following parts will be deleted: %1.\n")).arg(aPartFeatureNames.join(aSep));
1053 if (!anOtherFeatureNames.empty())
1054 aText += QString(QObject::tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n"))
1055 .arg(anOtherFeatureNames.join(aSep));
1056 if (!aParamFeatureNames.empty()) {
1057 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"))
1058 .arg(aParamFeatureNames.join(aSep));
1059 QPushButton *aReplaceButton = aMessageBox.addButton(QObject::tr("Replace"), QMessageBox::ActionRole);
1062 if (!aText.isEmpty()) {
1063 aText += "Would you like to continue?";
1064 aMessageBox.setText(aText);
1066 QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1068 if (aButtonRole == QMessageBox::NoRole)
1071 if (aButtonRole == QMessageBox::ActionRole) {
1072 foreach (FeaturePtr aObj, aParameterFeatures)
1073 ModelAPI_ReplaceParameterMessage::send(aObj, 0);
1076 theReferencesToDelete.insert(aFeaturesRefsToParameterOnly.begin(), aFeaturesRefsToParameterOnly.end());
1081 //**************************************************************
1082 void convertToFeatures(const QObjectPtrList& theObjects, std::set<FeaturePtr>& theFeatures)
1084 QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1085 for(; anIt != aLast; anIt++) {
1086 ObjectPtr anObject = *anIt;
1087 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1088 // for parameter result, use the corresponded reature to be removed
1089 if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1090 aFeature = ModelAPI_Feature::feature(anObject);
1092 theFeatures.insert(aFeature);
1096 } // namespace ModuleBase_Tools