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 <Events_InfoMessage.h>
39 #include <GeomAPI_ShapeExplorer.h>
41 #include <Config_PropManager.h>
42 #include <Config_Translator.h>
44 #include <Prs3d_PointAspect.hxx>
45 #include <Graphic3d_AspectMarker3d.hxx>
51 #include <QDoubleSpinBox>
52 #include <QGraphicsDropShadowEffect>
54 #include <QApplication>
55 #include <QMessageBox>
62 const double tolerance = 1e-7;
63 const double DEFAULT_DEVIATION_COEFFICIENT = 1.e-4;
65 //#define DEBUG_ACTIVATE_WINDOW
66 //#define DEBUG_SET_FOCUS
67 //#define DEBUG_SELECTION_INFO
69 #ifdef DEBUG_SELECTION_INFO
70 #include <ModuleBase_ISelection.h>
71 #include <ModuleBase_ViewerPrs.h>
73 #include <AIS_InteractiveContext.hxx>
74 #include <AIS_ListOfInteractive.hxx>
75 #include <AIS_ListIteratorOfListOfInteractive.hxx>
76 #include <AIS_Shape.hxx>
77 #include <TopoDS_Shape.hxx>
78 #include <AIS_LocalContext.hxx>
79 #include <NCollection_List.hxx>
80 #include <StdSelect_BRepOwner.hxx>
81 #include <TColStd_ListOfInteger.hxx>
82 #include <TColStd_ListIteratorOfListOfInteger.hxx>
85 namespace ModuleBase_Tools {
87 //******************************************************************
89 //******************************************************************
91 void adjustMargins(QWidget* theWidget)
95 adjustMargins(theWidget->layout());
98 void adjustMargins(QLayout* theLayout)
102 theLayout->setContentsMargins(2, 5, 2, 5);
103 theLayout->setSpacing(4);
106 void zeroMargins(QWidget* theWidget)
110 zeroMargins(theWidget->layout());
113 void zeroMargins(QLayout* theLayout)
117 theLayout->setContentsMargins(0, 0, 0, 0);
118 theLayout->setSpacing(5);
121 void activateWindow(QWidget* theWidget, const QString& theInfo)
123 theWidget->activateWindow();
125 #ifdef DEBUG_ACTIVATE_WINDOW
126 qDebug(QString("activateWindow: %1").arg(theInfo).toStdString().c_str());
130 void setFocus(QWidget* theWidget, const QString& theInfo)
132 theWidget->setFocus();
134 #ifdef DEBUG_SET_FOCUS
135 qDebug(QString("setFocus: %1").arg(theInfo).toStdString().c_str());
139 void setShadowEffect(QWidget* theWidget, const bool isSetEffect)
142 QGraphicsDropShadowEffect* aGlowEffect = new QGraphicsDropShadowEffect();
143 aGlowEffect->setOffset(.0);
144 aGlowEffect->setBlurRadius(10.0);
145 aGlowEffect->setColor(QColor(0, 170, 255)); // Light-blue color, #00AAFF
146 theWidget->setGraphicsEffect(aGlowEffect);
149 QGraphicsEffect* anEffect = theWidget->graphicsEffect();
151 anEffect->deleteLater();
152 theWidget->setGraphicsEffect(NULL);
156 QPixmap composite(const QString& theAdditionalIcon, const QString& theIcon)
158 QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
159 QImage anAditional(theAdditionalIcon);
164 int anAddWidth = anAditional.width();
165 int anAddHeight = anAditional.height();
167 int aWidth = anIcon.width();
168 int aHeight = anIcon.height();
170 int aStartWidthPos = aWidth - anAddWidth - 1;
171 int aStartHeightPos = aHeight - anAddHeight - 1;
173 for (int i = 0; i < anAddWidth && i + aStartWidthPos < aWidth; i++)
175 for (int j = 0; j < anAddHeight && j + aStartHeightPos < aHeight; j++)
177 if (qAlpha(anAditional.pixel(i, j)) > 0)
178 anIcon.setPixel(i + aStartWidthPos, j + aStartHeightPos, anAditional.pixel(i, j));
181 return QPixmap::fromImage(anIcon);
184 QPixmap lighter(const QString& theIcon, const int theLighterValue)
186 QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
190 QImage aResult = ModuleBase_IconFactory::loadImage(theIcon);
191 for (int i = 0; i < anIcon.width(); i++)
193 for (int j = 0; j < anIcon.height(); j++)
195 QRgb anRgb = anIcon.pixel(i, j);
196 QColor aPixelColor(qRed(anRgb), qGreen(anRgb), qBlue(anRgb),
197 qAlpha(aResult.pixel(i, j)));
199 QColor aLighterColor = aPixelColor.lighter(theLighterValue);
200 aResult.setPixel(i, j, qRgba(aLighterColor.red(), aLighterColor.green(),
201 aLighterColor.blue(), aLighterColor.alpha()));
204 return QPixmap::fromImage(aResult);
207 void setSpinText(ModuleBase_ParamSpinBox* theSpin, const QString& theText)
209 if (theSpin->text() == theText)
211 // In order to avoid extra text setting because it will
212 // reset cursor position in control
213 bool isBlocked = theSpin->blockSignals(true);
214 theSpin->setText(theText);
215 theSpin->blockSignals(isBlocked);
218 void setSpinValue(QDoubleSpinBox* theSpin, double theValue)
220 if (fabs(theSpin->value() - theValue) < tolerance)
222 bool isBlocked = theSpin->blockSignals(true);
223 theSpin->setValue(theValue);
224 theSpin->blockSignals(isBlocked);
227 void setSpinValue(ModuleBase_ParamSpinBox* theSpin, double theValue)
229 if (fabs(theSpin->value() - theValue) < tolerance)
231 bool isBlocked = theSpin->blockSignals(true);
232 theSpin->setValue(theValue);
233 theSpin->blockSignals(isBlocked);
236 void setSpinText(ModuleBase_ParamIntSpinBox* theSpin, const QString& theText)
238 // In order to avoid extra text setting because it will
239 // reset cursor position in control
240 if (theSpin->text() == theText)
242 bool isBlocked = theSpin->blockSignals(true);
243 theSpin->setText(theText);
244 theSpin->blockSignals(isBlocked);
247 void setSpinValue(ModuleBase_ParamIntSpinBox* theSpin, int theValue)
249 if (theSpin->value() == theValue)
251 bool isBlocked = theSpin->blockSignals(true);
252 theSpin->setValue(theValue);
253 theSpin->blockSignals(isBlocked);
256 QAction* createAction(const QIcon& theIcon, const QString& theText,
257 QObject* theParent, const QObject* theReceiver,
258 const char* theMember, const QString& theToolTip,
259 const QString& theStatusTip)
261 QAction* anAction = new QAction(theIcon, theText, theParent);
262 anAction->setToolTip(theToolTip.isEmpty() ? theText : theToolTip);
263 anAction->setStatusTip(!theStatusTip.isEmpty() ? theStatusTip :
264 (!theToolTip.isEmpty() ? theToolTip : theText));
266 QObject::connect(anAction, SIGNAL(triggered(bool)), theReceiver, theMember);
271 QString objectInfo(const ObjectPtr& theObj, const bool isUseAttributesInfo)
273 QString aFeatureStr = "feature";
277 std::ostringstream aPtrStr;
278 aPtrStr << "[" << theObj.get() << "]";
280 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theObj);
281 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
283 aFeatureStr.append(QString("(result%1)").arg(aPtrStr.str().c_str()).toStdString() .c_str());
284 if (aRes->isDisabled())
285 aFeatureStr.append("[disabled]");
286 if (aRes->isConcealed())
287 aFeatureStr.append("[concealed]");
288 if (ModelAPI_Tools::hasSubResults(aRes))
289 aFeatureStr.append("[hasSubResults]");
291 aFeature = ModelAPI_Feature::feature(aRes);
294 aFeatureStr.append(aPtrStr.str().c_str());
296 if (aFeature.get()) {
297 aFeatureStr.append(QString(": %1").arg(aFeature->getKind().c_str()).toStdString().c_str());
298 if (aFeature->data()->isValid()) {
299 aFeatureStr.append(QString(", name=%1").arg(theObj->data()->name().c_str()).toStdString()
302 if (isUseAttributesInfo) {
303 std::list<AttributePtr> anAttrs = aFeature->data()->attributes("");
304 std::list<AttributePtr>::const_iterator anIt = anAttrs.begin(), aLast = anAttrs.end();
306 for(; anIt != aLast; anIt++) {
307 AttributePtr anAttr = *anIt;
308 QString aValue = "not defined";
309 std::string aType = anAttr->attributeType();
310 if (aType == GeomDataAPI_Point2D::typeId()) {
311 std::shared_ptr<GeomDataAPI_Point2D> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
314 aValue = QString("(%1, %2)").arg(aPoint->x()).arg(aPoint->y());
316 else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
319 aValues.push_back(QString("%1: %2").arg(anAttr->id().c_str()).arg(aValue).toStdString().c_str());
321 if (!aValues.empty())
322 aFeatureStr.append(QString(", attributes: %1").arg(aValues.join(", ").toStdString().c_str()));
329 #ifdef DEBUG_SELECTION_INFO
330 QString getShapeTypeInfo(const int theType)
332 QString anInfo = "Undefined";
334 case TopAbs_COMPOUND: anInfo = "compound"; break;
335 case TopAbs_COMPSOLID: anInfo = "compsolid"; break;
336 case TopAbs_SOLID: anInfo = "solid"; break;
337 case TopAbs_SHELL: anInfo = "shell"; break;
338 case TopAbs_FACE: anInfo = "face"; break;
339 case TopAbs_WIRE: anInfo = "wire"; break;
340 case TopAbs_EDGE: anInfo = "edge"; break;
341 case TopAbs_VERTEX: anInfo = "vertex"; break;
342 case TopAbs_SHAPE: anInfo = "shape"; break;
348 QString getModeInfo(const int theMode)
350 QString anInfo = "Undefined";
352 case 0: anInfo = "SHAPE(0)"; break;
353 case 1: anInfo = "VERTEX(1)"; break;
354 case 2: anInfo = "EDGE(2)"; break;
355 case 3: anInfo = "WIRE(3)"; break;
356 case 4: anInfo = "FACE(4)"; break;
357 case 5: anInfo = "SHELL(5)"; break;
358 case 6: anInfo = "SOLID(6)"; break;
359 case 7: anInfo = "COMPSOLID(7)"; break;
360 case 8: anInfo = "COMPOUND(8)"; break;
361 case 100: anInfo = "Sel_Mode_First(100)"; break; //SketcherPrs_Tools
362 case 101: anInfo = "Sel_Constraint(101)"; break;
363 case 102: anInfo = "Sel_Dimension_All(102)"; break;
364 case 103: anInfo = "Sel_Dimension_Line(103)"; break;
365 case 104: anInfo = "Sel_Dimension_Text(104)"; break;
371 QString displayedInteractiveObjects(Handle(AIS_InteractiveContext)& theContext,
372 const bool theShapeInfoOnly = true)
374 if (theContext.IsNull())
376 AIS_ListOfInteractive aListOfIO;
377 theContext->DisplayedObjects(aListOfIO, false);
378 QStringList anObjects;
379 AIS_ListIteratorOfListOfInteractive aIt;
380 for (aIt.Initialize(aListOfIO); aIt.More(); aIt.Next()) {
381 Handle(AIS_InteractiveObject) anAISIO = aIt.Value();
382 Handle(AIS_Shape) aShapePrs = Handle(AIS_Shape)::DownCast(anAISIO);
383 if (theShapeInfoOnly && aShapePrs.IsNull())
386 QString anInfo = "IO";
387 std::ostringstream aPtrStr;
388 aPtrStr << "[" << anAISIO.Access() << "]";
389 anInfo += aPtrStr.str().c_str();
391 if (!aShapePrs.IsNull()) {
392 const TopoDS_Shape& aShape = aShapePrs->Shape();
394 Events_Error::throwException("An empty AIS presentation");
396 anInfo += QString(", shape type: %1").arg(getShapeTypeInfo(aShape.ShapeType()));
398 TColStd_ListOfInteger aTColModes;
399 theContext->ActivatedModes(anAISIO, aTColModes);
400 TColStd_ListIteratorOfListOfInteger itr( aTColModes );
401 QIntList aModesActivatedForIO;
402 bool isDeactivated = false;
404 for (; itr.More(); itr.Next() ) {
405 Standard_Integer aMode = itr.Value();
406 aModes.append(getModeInfo(aMode));
407 //int aShapeMode = (aMode > 8)? aMode : AIS_Shape::SelectionType(aMode);
409 if (aModes.size() > 0)
410 anInfo += QString(", activated modes: %1").arg(aModes.join(", "));
414 QString aValue = QString("displayedIO[%1]").arg(anObjects.size());
415 if (anObjects.size() > 0)
416 aValue += QString(":\n %1").arg(anObjects.join("\n "));
420 QString activeOwners(Handle(AIS_InteractiveContext)& theContext, const bool theShapeInfoOnly = true)
422 if (theContext.IsNull())
424 Handle(AIS_LocalContext) aLContext = theContext->LocalContext();
425 TCollection_AsciiString aSelectionName = aLContext->SelectionName();
426 aLContext->UnhilightPicked(Standard_False);
428 NCollection_List<Handle(SelectBasics_EntityOwner)> anActiveOwners;
429 aLContext->MainSelector()->ActiveOwners(anActiveOwners);
430 NCollection_List<Handle(SelectBasics_EntityOwner)>::Iterator anOwnersIt (anActiveOwners);
431 Handle(SelectMgr_EntityOwner) anOwner;
432 QStringList anObjects;
433 for (; anOwnersIt.More(); anOwnersIt.Next()) {
434 anOwner = Handle(SelectMgr_EntityOwner)::DownCast (anOwnersIt.Value());
435 Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
436 if (theShapeInfoOnly && BROwnr.IsNull())
439 QString anInfo = "Owner";
440 std::ostringstream aPtrStr;
441 aPtrStr << "[" << anOwner.Access() << "]";
442 anInfo += aPtrStr.str().c_str();
444 Handle(AIS_InteractiveObject) aAISObj =
445 Handle(AIS_InteractiveObject)::DownCast(anOwner->Selectable());
446 if (!aAISObj.IsNull()) {
447 std::ostringstream aPtrStr;
448 aPtrStr << "[" << aAISObj.Access() << "]";
449 anInfo += QString(", selectable(IO): %1").arg(aPtrStr.str().c_str());
452 if (!BROwnr.IsNull() && BROwnr->HasShape()) {
453 const TopoDS_Shape& aShape = BROwnr->Shape();
455 Events_Error::throwException("An empty AIS presentation");
457 anInfo += QString(", shape type: %1").arg(getShapeTypeInfo(aShape.ShapeType()));
461 QString aValue = QString("activeOwners[%1]").arg(anObjects.size());
462 if (anObjects.size() > 0)
463 aValue += QString(":\n %1").arg(anObjects.join("\n "));
467 QString selectedOwners(Handle(AIS_InteractiveContext)& theContext, const bool theShapeInfoOnly = true)
469 QStringList anObjects;
470 if (theContext.IsNull())
473 QList<long> aSelectedIds; // Remember of selected address in order to avoid duplicates
474 for (theContext->InitSelected(); theContext->MoreSelected(); theContext->NextSelected()) {
475 Handle(SelectMgr_EntityOwner) anOwner = theContext->SelectedOwner();
476 Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
477 if (theShapeInfoOnly && BROwnr.IsNull())
480 if (aSelectedIds.contains((long)anOwner.Access()))
482 aSelectedIds.append((long)anOwner.Access());
484 QString anInfo = "Owner";
485 std::ostringstream aPtrStr;
486 aPtrStr << "[" << anOwner.Access() << "]";
487 anInfo += aPtrStr.str().c_str();
489 if (!BROwnr.IsNull() && BROwnr->HasShape()) {
490 const TopoDS_Shape& aShape = BROwnr->Shape();
491 anInfo += QString(", shape type = %1").arg(getShapeTypeInfo(aShape.ShapeType()));
495 QString aValue = QString("selectedOwners[%1]").arg(anObjects.size());
496 if (anObjects.size() > 0)
497 aValue += QString(":\n %1").arg(anObjects.join("\n "));
502 void selectionInfo(Handle(AIS_InteractiveContext)& theContext, const std::string& thePrefix)
504 #ifdef DEBUG_SELECTION_INFO
505 QString aValue = QString("\n\n\nDEBUG_SELECTION_INFO for '%1'\n%2\n%3\n%4")
506 .arg(thePrefix.c_str())
507 .arg(displayedInteractiveObjects(theContext))
508 .arg(activeOwners(theContext))
509 .arg(selectedOwners(theContext));
510 qDebug(aValue.toStdString().c_str());
514 typedef QMap<QString, TopAbs_ShapeEnum> ShapeTypes;
515 static ShapeTypes myShapeTypes;
517 TopAbs_ShapeEnum shapeType(const QString& theType)
519 if (myShapeTypes.count() == 0) {
520 myShapeTypes["compound"] = TopAbs_COMPOUND;
521 myShapeTypes["compounds"] = TopAbs_COMPOUND;
522 myShapeTypes["compsolid"] = TopAbs_COMPSOLID;
523 myShapeTypes["compsolids"] = TopAbs_COMPSOLID;
524 myShapeTypes["solid"] = TopAbs_SOLID;
525 myShapeTypes["solids"] = TopAbs_SOLID;
526 myShapeTypes["shell"] = TopAbs_SHELL;
527 myShapeTypes["shells"] = TopAbs_SHELL;
528 myShapeTypes["face"] = TopAbs_FACE;
529 myShapeTypes["faces"] = TopAbs_FACE;
530 myShapeTypes["wire"] = TopAbs_WIRE;
531 myShapeTypes["wires"] = TopAbs_WIRE;
532 myShapeTypes["edge"] = TopAbs_EDGE;
533 myShapeTypes["edges"] = TopAbs_EDGE;
534 myShapeTypes["vertex"] = TopAbs_VERTEX;
535 myShapeTypes["vertices"] = TopAbs_VERTEX;
536 myShapeTypes["objects"] = TopAbs_SHAPE;
538 QString aType = theType.toLower();
539 if(myShapeTypes.contains(aType))
540 return myShapeTypes[aType];
541 Events_InfoMessage("ModuleBase_Tools", "Shape type defined in XML is not implemented!").send();
545 void checkObjects(const QObjectPtrList& theObjects, bool& hasResult, bool& hasFeature,
546 bool& hasParameter, bool& hasCompositeOwner)
550 hasParameter = false;
551 hasCompositeOwner = false;
552 foreach(ObjectPtr aObj, theObjects) {
553 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
554 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
555 ResultParameterPtr aConstruction = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aResult);
557 hasResult |= (aResult.get() != NULL);
558 hasFeature |= (aFeature.get() != NULL);
559 hasParameter |= (aConstruction.get() != NULL);
561 hasCompositeOwner |= (ModelAPI_Tools::compositeOwner(aFeature) != NULL);
562 if (hasFeature && hasResult && hasParameter && hasCompositeOwner)
567 bool setDefaultDeviationCoefficient(std::shared_ptr<GeomAPI_Shape> theGeomShape)
569 if (!theGeomShape.get())
571 // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
572 // correction of deviation for them should not influence to the application performance
573 GeomAPI_ShapeExplorer anExp(theGeomShape, GeomAPI_Shape::FACE);
574 bool anEmpty = anExp.empty();
575 return !anExp.more();
578 void setDefaultDeviationCoefficient(const std::shared_ptr<ModelAPI_Result>& theResult,
579 const Handle(Prs3d_Drawer)& theDrawer)
581 if (!theResult.get())
583 bool aUseDeviation = false;
585 std::string aResultGroup = theResult->groupName();
586 if (aResultGroup == ModelAPI_ResultConstruction::group())
587 aUseDeviation = true;
588 else if (aResultGroup == ModelAPI_ResultBody::group()) {
589 GeomShapePtr aGeomShape = theResult->shape();
590 if (aGeomShape.get())
591 aUseDeviation = setDefaultDeviationCoefficient(aGeomShape);
594 theDrawer->SetDeviationCoefficient(DEFAULT_DEVIATION_COEFFICIENT);
597 void setDefaultDeviationCoefficient(const TopoDS_Shape& theShape,
598 const Handle(Prs3d_Drawer)& theDrawer)
600 if (theShape.IsNull())
603 std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape());
604 aGeomShape->setImpl(new TopoDS_Shape(theShape));
605 if (setDefaultDeviationCoefficient(aGeomShape))
606 theDrawer->SetDeviationCoefficient(DEFAULT_DEVIATION_COEFFICIENT);
609 Quantity_Color color(const std::string& theSection,
610 const std::string& theName,
611 const std::string& theDefault)
613 std::vector<int> aColor = Config_PropManager::color(theSection, theName, theDefault);
614 return Quantity_Color(aColor[0] / 255., aColor[1] / 255., aColor[2] / 255., Quantity_TOC_RGB);
617 ObjectPtr getObject(const AttributePtr& theAttribute)
620 std::string anAttrType = theAttribute->attributeType();
621 if (anAttrType == ModelAPI_AttributeRefAttr::typeId()) {
622 AttributeRefAttrPtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
623 if (anAttr != NULL && anAttr->isObject())
624 anObject = anAttr->object();
626 if (anAttrType == ModelAPI_AttributeSelection::typeId()) {
627 AttributeSelectionPtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
629 anObject = anAttr->context();
631 if (anAttrType == ModelAPI_AttributeReference::typeId()) {
632 AttributeReferencePtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
633 if (anAttr.get() != NULL)
634 anObject = anAttr->value();
639 TopAbs_ShapeEnum getCompoundSubType(const TopoDS_Shape& theShape)
641 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
643 // for compounds check sub-shapes: it may be compound of needed type:
644 // Booleans may produce compounds of Solids
645 if (aShapeType == TopAbs_COMPOUND) {
646 for(TopoDS_Iterator aSubs(theShape); aSubs.More(); aSubs.Next()) {
647 if (!aSubs.Value().IsNull()) {
648 TopAbs_ShapeEnum aSubType = aSubs.Value().ShapeType();
649 if (aSubType == TopAbs_COMPOUND) { // compound of compound(s)
650 aShapeType = TopAbs_COMPOUND;
653 if (aShapeType == TopAbs_COMPOUND) {
654 aShapeType = aSubType;
655 } else if (aShapeType != aSubType) { // compound of shapes of different types
656 aShapeType = TopAbs_COMPOUND;
665 void getParameters(QStringList& theParameters)
667 theParameters.clear();
669 SessionPtr aSession = ModelAPI_Session::get();
670 std::list<DocumentPtr> aDocList;
671 DocumentPtr anActiveDocument = aSession->activeDocument();
672 DocumentPtr aRootDocument = aSession->moduleDocument();
673 aDocList.push_back(anActiveDocument);
674 if (anActiveDocument != aRootDocument) {
675 aDocList.push_back(aRootDocument);
677 std::string aGroupId = ModelAPI_ResultParameter::group();
678 for(std::list<DocumentPtr>::const_iterator it = aDocList.begin(); it != aDocList.end(); ++it) {
679 DocumentPtr aDocument = *it;
680 int aSize = aDocument->size(aGroupId);
681 for (int i = 0; i < aSize; i++) {
682 ObjectPtr anObject = aDocument->object(aGroupId, i);
683 std::string aParameterName = anObject->data()->name();
684 theParameters.append(aParameterName.c_str());
689 std::string findGreedAttribute(ModuleBase_IWorkshop* theWorkshop, const FeaturePtr& theFeature)
691 std::string anAttributeId;
693 std::string aXmlCfg, aDescription;
694 theWorkshop->module()->getXMLRepresentation(theFeature->getKind(), aXmlCfg, aDescription);
696 ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
697 std::string anAttributeTitle;
698 aFactory.getGreedAttribute(anAttributeId);
700 return anAttributeId;
703 bool hasObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
704 const std::shared_ptr<GeomAPI_Shape>& theShape,
705 ModuleBase_IWorkshop* theWorkshop,
706 const bool theTemporarily)
708 bool aHasObject = false;
709 if (!theAttribute.get())
712 std::string aType = theAttribute->attributeType();
713 if (aType == ModelAPI_AttributeReference::typeId()) {
714 AttributeReferencePtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
715 ObjectPtr aObject = aRef->value();
716 aHasObject = aObject && aObject->isSame(theObject);
717 //if (!(aObject && aObject->isSame(theObject))) {
718 // aRef->setValue(theObject);
720 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
721 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
723 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
724 if (anAttribute.get()) {
725 //aRefAttr->setAttr(anAttribute);
728 ObjectPtr aObject = aRefAttr->object();
729 aHasObject = aObject && aObject->isSame(theObject);
730 //if (!(aObject && aObject->isSame(theObject))) {
731 // aRefAttr->setObject(theObject);
734 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
735 /*AttributeSelectionPtr aSelectAttr =
736 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
737 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
738 if (aSelectAttr.get() != NULL) {
739 aSelectAttr->setValue(aResult, theShape, theTemporarily);
742 if (aType == ModelAPI_AttributeSelectionList::typeId()) {
743 AttributeSelectionListPtr aSelectionListAttr =
744 std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
745 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
746 aHasObject = aSelectionListAttr->isInList(aResult, theShape, theTemporarily);
747 //if (!theCheckIfAttributeHasObject || !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
748 // aSelectionListAttr->append(aResult, theShape, theTemporarily);
750 else if (aType == ModelAPI_AttributeRefList::typeId()) {
751 AttributeRefListPtr aRefListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
752 aHasObject = aRefListAttr->isInList(theObject);
753 //if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
754 // aRefListAttr->append(theObject);
756 else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
757 AttributeRefAttrListPtr aRefAttrListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
758 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
760 if (anAttribute.get()) {
761 aHasObject = aRefAttrListAttr->isInList(anAttribute);
762 //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
763 // aRefAttrListAttr->append(anAttribute);
766 aHasObject = aRefAttrListAttr->isInList(theObject);
767 //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
768 // aRefAttrListAttr->append(theObject);
774 void setObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
775 const GeomShapePtr& theShape, ModuleBase_IWorkshop* theWorkshop,
776 const bool theTemporarily, const bool theCheckIfAttributeHasObject)
778 if (!theAttribute.get())
781 std::string aType = theAttribute->attributeType();
782 if (aType == ModelAPI_AttributeReference::typeId()) {
783 AttributeReferencePtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
784 ObjectPtr aObject = aRef->value();
785 if (!(aObject && aObject->isSame(theObject))) {
786 aRef->setValue(theObject);
788 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
789 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
791 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
792 if (anAttribute.get())
793 aRefAttr->setAttr(anAttribute);
795 ObjectPtr aObject = aRefAttr->object();
796 if (!(aObject && aObject->isSame(theObject))) {
797 aRefAttr->setObject(theObject);
800 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
801 AttributeSelectionPtr aSelectAttr =
802 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
803 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
804 if (aSelectAttr.get() != NULL) {
805 aSelectAttr->setValue(aResult, theShape, theTemporarily);
808 if (aType == ModelAPI_AttributeSelectionList::typeId()) {
809 AttributeSelectionListPtr aSelectionListAttr =
810 std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
811 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
812 if (!theCheckIfAttributeHasObject || !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
813 aSelectionListAttr->append(aResult, theShape, theTemporarily);
815 else if (aType == ModelAPI_AttributeRefList::typeId()) {
816 AttributeRefListPtr aRefListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
817 if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
818 aRefListAttr->append(theObject);
820 else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
821 AttributeRefAttrListPtr aRefAttrListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
822 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
824 if (anAttribute.get()) {
825 if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
826 aRefAttrListAttr->append(anAttribute);
829 if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
830 aRefAttrListAttr->append(theObject);
835 GeomShapePtr getShape(const AttributePtr& theAttribute, ModuleBase_IWorkshop* theWorkshop)
838 if (!theAttribute.get())
841 std::string aType = theAttribute->attributeType();
842 if (aType == ModelAPI_AttributeReference::typeId()) {
843 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
844 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
845 if (aRefAttr.get() && !aRefAttr->isObject()) {
846 AttributePtr anAttribute = aRefAttr->attr();
847 aShape = theWorkshop->module()->findShape(anAttribute);
849 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
850 AttributeSelectionPtr aSelectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>
852 aShape = aSelectAttr->value();
857 void flushUpdated(ObjectPtr theObject)
859 blockUpdateViewer(true);
861 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
863 blockUpdateViewer(false);
866 void blockUpdateViewer(const bool theValue)
868 // the viewer update should be blocked in order to avoid the temporary feature content
869 // when the solver processes the feature, the redisplay message can be flushed
870 // what caused the display in the viewer preliminary states of object
871 // e.g. fillet feature, angle value change
872 std::shared_ptr<Events_Message> aMsg;
874 aMsg = std::shared_ptr<Events_Message>(
875 new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)));
878 // the viewer update should be unblocked
879 aMsg = std::shared_ptr<Events_Message>(
880 new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)));
882 Events_Loop::loop()->send(aMsg);
885 QString wrapTextByWords(const QString& theValue, QWidget* theWidget,
886 int theMaxLineInPixels)
888 static QFontMetrics tfm(theWidget ? theWidget->font() : QApplication::font());
889 static qreal phi = 2.618;
891 QRect aBounds = tfm.boundingRect(theValue);
892 if(aBounds.width() <= theMaxLineInPixels)
895 qreal s = aBounds.width() * aBounds.height();
896 qreal aGoldWidth = sqrt(s*phi);
898 QStringList aWords = theValue.split(" ", QString::SkipEmptyParts);
900 int n = aWords.count();
902 for (int i = 0; i < n; i++) {
903 QString aLineExt = aLine + " " + aWords[i];
904 qreal anWidthNonExt = tfm.boundingRect(aLine).width();
905 qreal anWidthExt = tfm.boundingRect(aLineExt).width();
906 qreal aDeltaNonExt = fabs(anWidthNonExt-aGoldWidth);
907 qreal aDeltaExt = fabs(anWidthExt-aGoldWidth);
908 if(aDeltaNonExt < aDeltaExt) {
910 aLines.append(aLine);
918 aLines.append(aLine);
920 QString aResult = aLines.join("\n");
924 //**************************************************************
925 void refsToFeatureInFeatureDocument(const ObjectPtr& theObject, std::set<FeaturePtr>& theRefFeatures)
927 FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
928 if (aFeature.get()) {
929 DocumentPtr aFeatureDoc = aFeature->document();
930 // 1. find references in the current document
931 aFeatureDoc->refsToFeature(aFeature, theRefFeatures, false);
936 //**************************************************************
937 bool isSubOfComposite(const ObjectPtr& theObject)
940 std::set<FeaturePtr> aRefFeatures;
941 refsToFeatureInFeatureDocument(theObject, aRefFeatures);
942 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
943 aLast = aRefFeatures.end();
944 for (; anIt != aLast && !isSub; anIt++) {
945 isSub = isSubOfComposite(theObject, *anIt);
950 //**************************************************************
951 bool isSubOfComposite(const ObjectPtr& theObject, const FeaturePtr& theFeature)
954 CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
955 if (aComposite.get()) {
956 isSub = aComposite->isSub(theObject);
957 // the recursive is possible, the parameters are sketch circle and extrusion cut. They are
958 // separated by composite sketch feature
960 int aNbSubs = aComposite->numberOfSubs();
961 for (int aSub = 0; aSub < aNbSubs && !isSub; aSub++) {
962 isSub = isSubOfComposite(theObject, aComposite->subFeature(aSub));
969 //**************************************************************
970 ResultPtr firstResult(const ObjectPtr& theObject)
972 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
973 if (!aResult.get()) {
974 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
976 aResult = aFeature->firstResult();
981 //**************************************************************
982 bool isFeatureOfResult(const FeaturePtr& theFeature, const std::string& theGroupOfResult)
984 bool isResult = false;
986 if (!theFeature->data()->isValid())
989 ResultPtr aFirstResult = theFeature->firstResult();
990 if (!aFirstResult.get())
993 return aFirstResult->groupName() == theGroupOfResult;
996 //**************************************************************
997 bool hasModuleDocumentFeature(const std::set<FeaturePtr>& theFeatures)
999 bool aFoundModuleDocumentObject = false;
1000 DocumentPtr aModuleDoc = ModelAPI_Session::get()->moduleDocument();
1002 std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(), aLast = theFeatures.end();
1003 for (; anIt != aLast && !aFoundModuleDocumentObject; anIt++) {
1004 FeaturePtr aFeature = *anIt;
1005 ResultPtr aResult = ModuleBase_Tools::firstResult(aFeature);
1006 if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group())
1008 aFoundModuleDocumentObject = aFeature->document() == aModuleDoc;
1011 return aFoundModuleDocumentObject;
1014 //**************************************************************
1015 bool askToDelete(const std::set<FeaturePtr> theFeatures,
1016 const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
1018 std::set<FeaturePtr>& theReferencesToDelete)
1020 QString aNotActivatedDocWrn;
1021 std::string aNotActivatedNames;
1022 if (!ModelAPI_Tools::allDocumentsActivated(aNotActivatedNames)) {
1023 if (ModuleBase_Tools::hasModuleDocumentFeature(theFeatures))
1024 aNotActivatedDocWrn = QObject::tr("Selected objects can be used in Part documents which are not loaded:%1.\n")
1025 .arg(aNotActivatedNames.c_str());
1028 std::set<FeaturePtr> aFeaturesRefsTo;
1029 std::set<FeaturePtr> aFeaturesRefsToParameter;
1030 std::set<FeaturePtr> aParameterFeatures;
1031 QStringList aPartFeatureNames;
1032 std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
1033 aLast = theFeatures.end();
1034 // separate features to references to parameter features and references to others
1035 for (; anIt != aLast; anIt++) {
1036 FeaturePtr aFeature = *anIt;
1037 if (theReferences.find(aFeature) == theReferences.end())
1040 if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
1041 aPartFeatureNames.append(aFeature->name().c_str());
1043 std::set<FeaturePtr> aRefFeatures;
1044 std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
1045 std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
1046 for (; aRefIt != aRefLast; aRefIt++) {
1047 FeaturePtr aRefFeature = *aRefIt;
1048 if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
1049 aRefFeatures.find(aRefFeature) == aRefFeatures.end()) // it is not added
1050 aRefFeatures.insert(aRefFeature);
1053 if (isFeatureOfResult(aFeature, ModelAPI_ResultParameter::group())) {
1054 aFeaturesRefsToParameter.insert(aRefFeatures.begin(), aRefFeatures.end());
1055 aParameterFeatures.insert(aFeature);
1058 theReferencesToDelete.insert(aRefFeatures.begin(), aRefFeatures.end());
1062 std::set<FeaturePtr> aFeaturesRefsToParameterOnly;
1063 anIt = aFeaturesRefsToParameter.begin();
1064 aLast = aFeaturesRefsToParameter.end();
1065 // separate features to references to parameter features and references to others
1066 QStringList aParamFeatureNames;
1067 for (; anIt != aLast; anIt++) {
1068 FeaturePtr aFeature = *anIt;
1069 if (theReferencesToDelete.find(aFeature) == theReferencesToDelete.end()) {
1070 aFeaturesRefsToParameterOnly.insert(aFeature);
1071 aParamFeatureNames.append(aFeature->name().c_str());
1074 aParamFeatureNames.sort();
1075 QStringList anOtherFeatureNames;
1076 anIt = theReferencesToDelete.begin();
1077 aLast = theReferencesToDelete.end();
1078 for (; anIt != aLast; anIt++) {
1079 FeaturePtr aFeature = *anIt;
1080 if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
1081 aPartFeatureNames.append(aFeature->name().c_str());
1083 anOtherFeatureNames.append(aFeature->name().c_str());
1085 aPartFeatureNames.sort();
1086 anOtherFeatureNames.sort();
1088 bool aCanReplaceParameters = !aFeaturesRefsToParameterOnly.empty();
1090 QMessageBox aMessageBox(theParent);
1091 aMessageBox.setWindowTitle(QObject::tr("Delete features"));
1092 aMessageBox.setIcon(QMessageBox::Warning);
1093 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1094 aMessageBox.setDefaultButton(QMessageBox::No);
1097 QString aSep = ", ";
1098 if (!aPartFeatureNames.empty())
1099 aText += QString(QObject::tr("The following parts will be deleted: %1.\n")).arg(aPartFeatureNames.join(aSep));
1100 if (!aNotActivatedDocWrn.isEmpty())
1101 aText += aNotActivatedDocWrn;
1102 if (!anOtherFeatureNames.empty())
1103 aText += QString(QObject::tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n"))
1104 .arg(anOtherFeatureNames.join(aSep));
1105 if (!aParamFeatureNames.empty()) {
1106 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"))
1107 .arg(aParamFeatureNames.join(aSep));
1108 QPushButton *aReplaceButton = aMessageBox.addButton(QObject::tr("Replace"), QMessageBox::ActionRole);
1111 if (!aText.isEmpty()) {
1112 aText += "Would you like to continue?";
1113 aMessageBox.setText(aText);
1115 QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1117 if (aButtonRole == QMessageBox::NoRole)
1120 if (aButtonRole == QMessageBox::ActionRole) {
1121 foreach (FeaturePtr aObj, aParameterFeatures)
1122 ModelAPI_ReplaceParameterMessage::send(aObj, 0);
1125 theReferencesToDelete.insert(aFeaturesRefsToParameterOnly.begin(), aFeaturesRefsToParameterOnly.end());
1130 //**************************************************************
1131 void convertToFeatures(const QObjectPtrList& theObjects, std::set<FeaturePtr>& theFeatures)
1133 QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1134 for(; anIt != aLast; anIt++) {
1135 ObjectPtr anObject = *anIt;
1136 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1137 // for parameter result, use the corresponded reature to be removed
1138 if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1139 aFeature = ModelAPI_Feature::feature(anObject);
1141 theFeatures.insert(aFeature);
1145 void translate(const std::string& theContext, std::string& theMessage)
1147 if (!theMessage.empty()) {
1148 std::string aStr = Config_Translator::translate(theContext, theMessage);
1149 if (!aStr.empty()) {
1150 std::string aCodec = Config_Translator::codec(theContext);
1151 theMessage = QTextCodec::codecForName(aCodec.c_str())->toUnicode(aStr.c_str()).toStdString();
1156 void setPointBallHighlighting(AIS_Shape* theAIS)
1158 Handle(Prs3d_Drawer) aDrawer = theAIS->HilightAttributes();
1159 if (aDrawer->HasOwnPointAspect()) {
1160 Handle(Prs3d_PointAspect) aPntAspect = aDrawer->PointAspect();
1161 aPntAspect->Aspect()->SetType(Aspect_TOM_BALL);
1162 aDrawer->SetPointAspect(aPntAspect);
1163 theAIS->SetHilightAttributes(aDrawer);
1167 } // namespace ModuleBase_Tools