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>
47 #include <Image_AlienPixMap.hxx>
53 #include <QDoubleSpinBox>
54 #include <QGraphicsDropShadowEffect>
56 #include <QApplication>
57 #include <QMessageBox>
64 const double tolerance = 1e-7;
65 const double DEFAULT_DEVIATION_COEFFICIENT = 1.e-4;
67 //#define DEBUG_ACTIVATE_WINDOW
68 //#define DEBUG_SET_FOCUS
69 //#define DEBUG_SELECTION_INFO
71 #ifdef DEBUG_SELECTION_INFO
72 #include <ModuleBase_ISelection.h>
73 #include <ModuleBase_ViewerPrs.h>
75 #include <AIS_InteractiveContext.hxx>
76 #include <AIS_ListOfInteractive.hxx>
77 #include <AIS_ListIteratorOfListOfInteractive.hxx>
78 #include <AIS_Shape.hxx>
79 #include <TopoDS_Shape.hxx>
80 #include <AIS_LocalContext.hxx>
81 #include <NCollection_List.hxx>
82 #include <StdSelect_BRepOwner.hxx>
83 #include <TColStd_ListOfInteger.hxx>
84 #include <TColStd_ListIteratorOfListOfInteger.hxx>
93 namespace ModuleBase_Tools {
95 //******************************************************************
97 //******************************************************************
99 void adjustMargins(QWidget* theWidget)
103 adjustMargins(theWidget->layout());
106 void adjustMargins(QLayout* theLayout)
110 theLayout->setContentsMargins(2, 5, 2, 5);
111 theLayout->setSpacing(4);
114 void zeroMargins(QWidget* theWidget)
118 zeroMargins(theWidget->layout());
121 void zeroMargins(QLayout* theLayout)
125 theLayout->setContentsMargins(0, 0, 0, 0);
126 theLayout->setSpacing(5);
129 void activateWindow(QWidget* theWidget, const QString& theInfo)
131 theWidget->activateWindow();
133 #ifdef DEBUG_ACTIVATE_WINDOW
134 qDebug(QString("activateWindow: %1").arg(theInfo).toStdString().c_str());
138 void setFocus(QWidget* theWidget, const QString& theInfo)
140 theWidget->setFocus();
142 #ifdef DEBUG_SET_FOCUS
143 qDebug(QString("setFocus: %1").arg(theInfo).toStdString().c_str());
147 void setShadowEffect(QWidget* theWidget, const bool isSetEffect)
150 QGraphicsDropShadowEffect* aGlowEffect = new QGraphicsDropShadowEffect();
151 aGlowEffect->setOffset(.0);
152 aGlowEffect->setBlurRadius(10.0);
153 aGlowEffect->setColor(QColor(0, 170, 255)); // Light-blue color, #00AAFF
154 theWidget->setGraphicsEffect(aGlowEffect);
157 QGraphicsEffect* anEffect = theWidget->graphicsEffect();
159 anEffect->deleteLater();
160 theWidget->setGraphicsEffect(NULL);
164 QPixmap composite(const QString& theAdditionalIcon, const QString& theIcon)
166 QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
167 QImage anAditional(theAdditionalIcon);
172 int anAddWidth = anAditional.width();
173 int anAddHeight = anAditional.height();
175 int aWidth = anIcon.width();
176 int aHeight = anIcon.height();
178 int aStartWidthPos = aWidth - anAddWidth - 1;
179 int aStartHeightPos = aHeight - anAddHeight - 1;
181 for (int i = 0; i < anAddWidth && i + aStartWidthPos < aWidth; i++)
183 for (int j = 0; j < anAddHeight && j + aStartHeightPos < aHeight; j++)
185 if (qAlpha(anAditional.pixel(i, j)) > 0)
186 anIcon.setPixel(i + aStartWidthPos, j + aStartHeightPos, anAditional.pixel(i, j));
189 return QPixmap::fromImage(anIcon);
192 QPixmap lighter(const QString& theIcon, const int theLighterValue)
194 QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
198 QImage aResult = ModuleBase_IconFactory::loadImage(theIcon);
199 for (int i = 0; i < anIcon.width(); i++)
201 for (int j = 0; j < anIcon.height(); j++)
203 QRgb anRgb = anIcon.pixel(i, j);
204 QColor aPixelColor(qRed(anRgb), qGreen(anRgb), qBlue(anRgb),
205 qAlpha(aResult.pixel(i, j)));
207 QColor aLighterColor = aPixelColor.lighter(theLighterValue);
208 aResult.setPixel(i, j, qRgba(aLighterColor.red(), aLighterColor.green(),
209 aLighterColor.blue(), aLighterColor.alpha()));
212 return QPixmap::fromImage(aResult);
215 void setSpinText(ModuleBase_ParamSpinBox* theSpin, const QString& theText)
217 if (theSpin->text() == theText)
219 // In order to avoid extra text setting because it will
220 // reset cursor position in control
221 bool isBlocked = theSpin->blockSignals(true);
222 theSpin->setText(theText);
223 theSpin->blockSignals(isBlocked);
226 void setSpinValue(QDoubleSpinBox* theSpin, double theValue)
228 if (fabs(theSpin->value() - theValue) < tolerance)
230 bool isBlocked = theSpin->blockSignals(true);
231 theSpin->setValue(theValue);
232 theSpin->blockSignals(isBlocked);
235 void setSpinValue(ModuleBase_ParamSpinBox* theSpin, double theValue)
237 if (fabs(theSpin->value() - theValue) < tolerance)
239 bool isBlocked = theSpin->blockSignals(true);
240 theSpin->setValue(theValue);
241 theSpin->blockSignals(isBlocked);
244 void setSpinText(ModuleBase_ParamIntSpinBox* theSpin, const QString& theText)
246 // In order to avoid extra text setting because it will
247 // reset cursor position in control
248 if (theSpin->text() == theText)
250 bool isBlocked = theSpin->blockSignals(true);
251 theSpin->setText(theText);
252 theSpin->blockSignals(isBlocked);
255 void setSpinValue(ModuleBase_ParamIntSpinBox* theSpin, int theValue)
257 if (theSpin->value() == theValue)
259 bool isBlocked = theSpin->blockSignals(true);
260 theSpin->setValue(theValue);
261 theSpin->blockSignals(isBlocked);
264 QAction* createAction(const QIcon& theIcon, const QString& theText,
265 QObject* theParent, const QObject* theReceiver,
266 const char* theMember, const QString& theToolTip,
267 const QString& theStatusTip)
269 QAction* anAction = new QAction(theIcon, theText, theParent);
270 anAction->setToolTip(theToolTip.isEmpty() ? theText : theToolTip);
271 anAction->setStatusTip(!theStatusTip.isEmpty() ? theStatusTip :
272 (!theToolTip.isEmpty() ? theToolTip : theText));
274 QObject::connect(anAction, SIGNAL(triggered(bool)), theReceiver, theMember);
279 QString objectInfo(const ObjectPtr& theObj, const bool isUseAttributesInfo)
281 QString aFeatureStr = "feature";
285 std::ostringstream aPtrStr;
286 aPtrStr << "[" << theObj.get() << "]";
288 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theObj);
289 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
291 aFeatureStr.append(QString("(result%1)").arg(aPtrStr.str().c_str()).toStdString() .c_str());
292 if (aRes->isDisabled())
293 aFeatureStr.append("[disabled]");
294 if (aRes->isConcealed())
295 aFeatureStr.append("[concealed]");
296 if (ModelAPI_Tools::hasSubResults(aRes))
297 aFeatureStr.append("[hasSubResults]");
299 aFeature = ModelAPI_Feature::feature(aRes);
302 aFeatureStr.append(aPtrStr.str().c_str());
304 if (aFeature.get()) {
305 aFeatureStr.append(QString(": %1").arg(aFeature->getKind().c_str()).toStdString().c_str());
306 if (aFeature->data()->isValid()) {
307 aFeatureStr.append(QString(", name=%1").arg(theObj->data()->name().c_str()).toStdString()
310 if (isUseAttributesInfo) {
311 std::list<AttributePtr> anAttrs = aFeature->data()->attributes("");
312 std::list<AttributePtr>::const_iterator anIt = anAttrs.begin(), aLast = anAttrs.end();
314 for(; anIt != aLast; anIt++) {
315 AttributePtr anAttr = *anIt;
316 QString aValue = "not defined";
317 std::string aType = anAttr->attributeType();
318 if (aType == GeomDataAPI_Point2D::typeId()) {
319 std::shared_ptr<GeomDataAPI_Point2D> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
322 aValue = QString("(%1, %2)").arg(aPoint->x()).arg(aPoint->y());
324 else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
327 aValues.push_back(QString("%1: %2").arg(anAttr->id().c_str()).arg(aValue).toStdString().c_str());
329 if (!aValues.empty())
330 aFeatureStr.append(QString(", attributes: %1").arg(aValues.join(", ").toStdString().c_str()));
337 #ifdef DEBUG_SELECTION_INFO
338 QString getShapeTypeInfo(const int theType)
340 QString anInfo = "Undefined";
342 case TopAbs_COMPOUND: anInfo = "compound"; break;
343 case TopAbs_COMPSOLID: anInfo = "compsolid"; break;
344 case TopAbs_SOLID: anInfo = "solid"; break;
345 case TopAbs_SHELL: anInfo = "shell"; break;
346 case TopAbs_FACE: anInfo = "face"; break;
347 case TopAbs_WIRE: anInfo = "wire"; break;
348 case TopAbs_EDGE: anInfo = "edge"; break;
349 case TopAbs_VERTEX: anInfo = "vertex"; break;
350 case TopAbs_SHAPE: anInfo = "shape"; break;
356 QString getModeInfo(const int theMode)
358 QString anInfo = "Undefined";
360 case 0: anInfo = "SHAPE(0)"; break;
361 case 1: anInfo = "VERTEX(1)"; break;
362 case 2: anInfo = "EDGE(2)"; break;
363 case 3: anInfo = "WIRE(3)"; break;
364 case 4: anInfo = "FACE(4)"; break;
365 case 5: anInfo = "SHELL(5)"; break;
366 case 6: anInfo = "SOLID(6)"; break;
367 case 7: anInfo = "COMPSOLID(7)"; break;
368 case 8: anInfo = "COMPOUND(8)"; break;
369 case 100: anInfo = "Sel_Mode_First(100)"; break; //SketcherPrs_Tools
370 case 101: anInfo = "Sel_Constraint(101)"; break;
371 case 102: anInfo = "Sel_Dimension_All(102)"; break;
372 case 103: anInfo = "Sel_Dimension_Line(103)"; break;
373 case 104: anInfo = "Sel_Dimension_Text(104)"; break;
379 QString displayedInteractiveObjects(Handle(AIS_InteractiveContext)& theContext,
380 const bool theShapeInfoOnly = true)
382 if (theContext.IsNull())
384 AIS_ListOfInteractive aListOfIO;
385 theContext->DisplayedObjects(aListOfIO, false);
386 QStringList anObjects;
387 AIS_ListIteratorOfListOfInteractive aIt;
388 for (aIt.Initialize(aListOfIO); aIt.More(); aIt.Next()) {
389 Handle(AIS_InteractiveObject) anAISIO = aIt.Value();
390 Handle(AIS_Shape) aShapePrs = Handle(AIS_Shape)::DownCast(anAISIO);
391 if (theShapeInfoOnly && aShapePrs.IsNull())
394 QString anInfo = "IO";
395 std::ostringstream aPtrStr;
396 aPtrStr << "[" << anAISIO.Access() << "]";
397 anInfo += aPtrStr.str().c_str();
399 if (!aShapePrs.IsNull()) {
400 const TopoDS_Shape& aShape = aShapePrs->Shape();
401 if (aShape.IsNull()) {
402 //Events_Error::throwException("An empty AIS presentation");
405 anInfo += QString(", shape type: %1").arg(getShapeTypeInfo(aShape.ShapeType()));
407 TColStd_ListOfInteger aTColModes;
408 theContext->ActivatedModes(anAISIO, aTColModes);
409 TColStd_ListIteratorOfListOfInteger itr( aTColModes );
410 QIntList aModesActivatedForIO;
411 bool isDeactivated = false;
413 for (; itr.More(); itr.Next() ) {
414 Standard_Integer aMode = itr.Value();
415 aModes.append(getModeInfo(aMode));
416 //int aShapeMode = (aMode > 8)? aMode : AIS_Shape::SelectionType(aMode);
418 if (aModes.size() > 0)
419 anInfo += QString(", activated modes: %1").arg(aModes.join(", "));
423 QString aValue = QString("displayedIO[%1]").arg(anObjects.size());
424 if (anObjects.size() > 0)
425 aValue += QString(":\n %1").arg(anObjects.join("\n "));
429 QString activeOwners(Handle(AIS_InteractiveContext)& theContext, const bool theShapeInfoOnly = true)
431 if (theContext.IsNull())
433 Handle(AIS_LocalContext) aLContext = theContext->LocalContext();
434 TCollection_AsciiString aSelectionName = aLContext->SelectionName();
435 aLContext->UnhilightPicked(Standard_False);
437 NCollection_List<Handle(SelectBasics_EntityOwner)> anActiveOwners;
438 aLContext->MainSelector()->ActiveOwners(anActiveOwners);
439 NCollection_List<Handle(SelectBasics_EntityOwner)>::Iterator anOwnersIt (anActiveOwners);
440 Handle(SelectMgr_EntityOwner) anOwner;
441 QStringList anObjects;
442 for (; anOwnersIt.More(); anOwnersIt.Next()) {
443 anOwner = Handle(SelectMgr_EntityOwner)::DownCast (anOwnersIt.Value());
444 Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
445 if (theShapeInfoOnly && BROwnr.IsNull())
448 QString anInfo = "Owner";
449 std::ostringstream aPtrStr;
450 aPtrStr << "[" << anOwner.Access() << "]";
451 anInfo += aPtrStr.str().c_str();
453 Handle(AIS_InteractiveObject) aAISObj =
454 Handle(AIS_InteractiveObject)::DownCast(anOwner->Selectable());
455 if (!aAISObj.IsNull()) {
456 std::ostringstream aPtrStr;
457 aPtrStr << "[" << aAISObj.Access() << "]";
458 anInfo += QString(", selectable(IO): %1").arg(aPtrStr.str().c_str());
461 if (!BROwnr.IsNull() && BROwnr->HasShape()) {
462 const TopoDS_Shape& aShape = BROwnr->Shape();
463 if (aShape.IsNull()) {
464 //Events_Error::throwException("An empty AIS presentation");
467 anInfo += QString(", shape type: %1").arg(getShapeTypeInfo(aShape.ShapeType()));
471 QString aValue = QString("activeOwners[%1]").arg(anObjects.size());
472 if (anObjects.size() > 0)
473 aValue += QString(":\n %1").arg(anObjects.join("\n "));
477 QString selectedOwners(Handle(AIS_InteractiveContext)& theContext, const bool theShapeInfoOnly = true)
479 QStringList anObjects;
480 if (theContext.IsNull())
483 QList<long> aSelectedIds; // Remember of selected address in order to avoid duplicates
484 for (theContext->InitSelected(); theContext->MoreSelected(); theContext->NextSelected()) {
485 Handle(SelectMgr_EntityOwner) anOwner = theContext->SelectedOwner();
486 Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
487 if (theShapeInfoOnly && BROwnr.IsNull())
490 if (aSelectedIds.contains((long)anOwner.Access()))
492 aSelectedIds.append((long)anOwner.Access());
494 QString anInfo = "Owner";
495 std::ostringstream aPtrStr;
496 aPtrStr << "[" << anOwner.Access() << "]";
497 anInfo += aPtrStr.str().c_str();
499 if (!BROwnr.IsNull() && BROwnr->HasShape()) {
500 const TopoDS_Shape& aShape = BROwnr->Shape();
501 anInfo += QString(", shape type = %1").arg(getShapeTypeInfo(aShape.ShapeType()));
505 QString aValue = QString("selectedOwners[%1]").arg(anObjects.size());
506 if (anObjects.size() > 0)
507 aValue += QString(":\n %1").arg(anObjects.join("\n "));
512 void selectionInfo(Handle(AIS_InteractiveContext)& theContext, const std::string& thePrefix)
514 #ifdef DEBUG_SELECTION_INFO
515 QString aValue = QString("\n\n\nDEBUG_SELECTION_INFO for '%1'\n%2\n%3\n%4")
516 .arg(thePrefix.c_str())
517 .arg(displayedInteractiveObjects(theContext))
518 .arg(activeOwners(theContext))
519 .arg(selectedOwners(theContext));
520 qDebug(aValue.toStdString().c_str());
524 typedef QMap<QString, TopAbs_ShapeEnum> ShapeTypes;
525 static ShapeTypes myShapeTypes;
527 TopAbs_ShapeEnum shapeType(const QString& theType)
529 if (myShapeTypes.count() == 0) {
530 myShapeTypes["compound"] = TopAbs_COMPOUND;
531 myShapeTypes["compounds"] = TopAbs_COMPOUND;
532 myShapeTypes["compsolid"] = TopAbs_COMPSOLID;
533 myShapeTypes["compsolids"] = TopAbs_COMPSOLID;
534 myShapeTypes["solid"] = TopAbs_SOLID;
535 myShapeTypes["solids"] = TopAbs_SOLID;
536 myShapeTypes["shell"] = TopAbs_SHELL;
537 myShapeTypes["shells"] = TopAbs_SHELL;
538 myShapeTypes["face"] = TopAbs_FACE;
539 myShapeTypes["faces"] = TopAbs_FACE;
540 myShapeTypes["wire"] = TopAbs_WIRE;
541 myShapeTypes["wires"] = TopAbs_WIRE;
542 myShapeTypes["edge"] = TopAbs_EDGE;
543 myShapeTypes["edges"] = TopAbs_EDGE;
544 myShapeTypes["vertex"] = TopAbs_VERTEX;
545 myShapeTypes["vertices"] = TopAbs_VERTEX;
546 myShapeTypes["objects"] = TopAbs_SHAPE;
548 QString aType = theType.toLower();
549 if(myShapeTypes.contains(aType))
550 return myShapeTypes[aType];
551 Events_InfoMessage("ModuleBase_Tools", "Shape type defined in XML is not implemented!").send();
555 void checkObjects(const QObjectPtrList& theObjects, bool& hasResult, bool& hasFeature,
556 bool& hasParameter, bool& hasCompositeOwner)
560 hasParameter = false;
561 hasCompositeOwner = false;
562 foreach(ObjectPtr aObj, theObjects) {
563 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
564 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
565 ResultParameterPtr aConstruction = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aResult);
567 hasResult |= (aResult.get() != NULL);
568 hasFeature |= (aFeature.get() != NULL);
569 hasParameter |= (aConstruction.get() != NULL);
571 hasCompositeOwner |= (ModelAPI_Tools::compositeOwner(aFeature) != NULL);
572 if (hasFeature && hasResult && hasParameter && hasCompositeOwner)
577 bool setDefaultDeviationCoefficient(std::shared_ptr<GeomAPI_Shape> theGeomShape)
579 if (!theGeomShape.get())
581 // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
582 // correction of deviation for them should not influence to the application performance
583 GeomAPI_ShapeExplorer anExp(theGeomShape, GeomAPI_Shape::FACE);
584 bool anEmpty = anExp.empty();
585 return !anExp.more();
588 void setDefaultDeviationCoefficient(const std::shared_ptr<ModelAPI_Result>& theResult,
589 const Handle(Prs3d_Drawer)& theDrawer)
591 if (!theResult.get())
593 bool aUseDeviation = false;
595 std::string aResultGroup = theResult->groupName();
596 if (aResultGroup == ModelAPI_ResultConstruction::group())
597 aUseDeviation = true;
598 else if (aResultGroup == ModelAPI_ResultBody::group()) {
599 GeomShapePtr aGeomShape = theResult->shape();
600 if (aGeomShape.get())
601 aUseDeviation = setDefaultDeviationCoefficient(aGeomShape);
604 theDrawer->SetDeviationCoefficient(DEFAULT_DEVIATION_COEFFICIENT);
607 void setDefaultDeviationCoefficient(const TopoDS_Shape& theShape,
608 const Handle(Prs3d_Drawer)& theDrawer)
610 if (theShape.IsNull())
613 std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape());
614 aGeomShape->setImpl(new TopoDS_Shape(theShape));
615 if (setDefaultDeviationCoefficient(aGeomShape))
616 theDrawer->SetDeviationCoefficient(DEFAULT_DEVIATION_COEFFICIENT);
619 Quantity_Color color(const std::string& theSection,
620 const std::string& theName,
621 const std::string& theDefault)
623 std::vector<int> aColor = Config_PropManager::color(theSection, theName, theDefault);
624 return Quantity_Color(aColor[0] / 255., aColor[1] / 255., aColor[2] / 255., Quantity_TOC_RGB);
627 ObjectPtr getObject(const AttributePtr& theAttribute)
630 std::string anAttrType = theAttribute->attributeType();
631 if (anAttrType == ModelAPI_AttributeRefAttr::typeId()) {
632 AttributeRefAttrPtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
633 if (anAttr != NULL && anAttr->isObject())
634 anObject = anAttr->object();
636 if (anAttrType == ModelAPI_AttributeSelection::typeId()) {
637 AttributeSelectionPtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
639 anObject = anAttr->context();
641 if (anAttrType == ModelAPI_AttributeReference::typeId()) {
642 AttributeReferencePtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
643 if (anAttr.get() != NULL)
644 anObject = anAttr->value();
649 TopAbs_ShapeEnum getCompoundSubType(const TopoDS_Shape& theShape)
651 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
653 // for compounds check sub-shapes: it may be compound of needed type:
654 // Booleans may produce compounds of Solids
655 if (aShapeType == TopAbs_COMPOUND) {
656 for(TopoDS_Iterator aSubs(theShape); aSubs.More(); aSubs.Next()) {
657 if (!aSubs.Value().IsNull()) {
658 TopAbs_ShapeEnum aSubType = aSubs.Value().ShapeType();
659 if (aSubType == TopAbs_COMPOUND) { // compound of compound(s)
660 aShapeType = TopAbs_COMPOUND;
663 if (aShapeType == TopAbs_COMPOUND) {
664 aShapeType = aSubType;
665 } else if (aShapeType != aSubType) { // compound of shapes of different types
666 aShapeType = TopAbs_COMPOUND;
675 void getParameters(QStringList& theParameters)
677 theParameters.clear();
679 SessionPtr aSession = ModelAPI_Session::get();
680 std::list<DocumentPtr> aDocList;
681 DocumentPtr anActiveDocument = aSession->activeDocument();
682 DocumentPtr aRootDocument = aSession->moduleDocument();
683 aDocList.push_back(anActiveDocument);
684 if (anActiveDocument != aRootDocument) {
685 aDocList.push_back(aRootDocument);
687 std::string aGroupId = ModelAPI_ResultParameter::group();
688 for(std::list<DocumentPtr>::const_iterator it = aDocList.begin(); it != aDocList.end(); ++it) {
689 DocumentPtr aDocument = *it;
690 int aSize = aDocument->size(aGroupId);
691 for (int i = 0; i < aSize; i++) {
692 ObjectPtr anObject = aDocument->object(aGroupId, i);
693 std::string aParameterName = anObject->data()->name();
694 theParameters.append(aParameterName.c_str());
699 std::string findGreedAttribute(ModuleBase_IWorkshop* theWorkshop, const FeaturePtr& theFeature)
701 std::string anAttributeId;
703 std::string aXmlCfg, aDescription;
704 theWorkshop->module()->getXMLRepresentation(theFeature->getKind(), aXmlCfg, aDescription);
706 ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
707 std::string anAttributeTitle;
708 aFactory.getGreedAttribute(anAttributeId);
710 return anAttributeId;
713 bool hasObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
714 const std::shared_ptr<GeomAPI_Shape>& theShape,
715 ModuleBase_IWorkshop* theWorkshop,
716 const bool theTemporarily)
718 bool aHasObject = false;
719 if (!theAttribute.get())
722 std::string aType = theAttribute->attributeType();
723 if (aType == ModelAPI_AttributeReference::typeId()) {
724 AttributeReferencePtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
725 ObjectPtr aObject = aRef->value();
726 aHasObject = aObject && aObject->isSame(theObject);
727 //if (!(aObject && aObject->isSame(theObject))) {
728 // aRef->setValue(theObject);
730 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
731 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
733 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
734 if (anAttribute.get()) {
735 //aRefAttr->setAttr(anAttribute);
738 ObjectPtr aObject = aRefAttr->object();
739 aHasObject = aObject && aObject->isSame(theObject);
740 //if (!(aObject && aObject->isSame(theObject))) {
741 // aRefAttr->setObject(theObject);
744 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
745 /*AttributeSelectionPtr aSelectAttr =
746 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
747 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
748 if (aSelectAttr.get() != NULL) {
749 aSelectAttr->setValue(aResult, theShape, theTemporarily);
752 if (aType == ModelAPI_AttributeSelectionList::typeId()) {
753 AttributeSelectionListPtr aSelectionListAttr =
754 std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
755 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
756 aHasObject = aSelectionListAttr->isInList(aResult, theShape, theTemporarily);
757 //if (!theCheckIfAttributeHasObject || !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
758 // aSelectionListAttr->append(aResult, theShape, theTemporarily);
760 else if (aType == ModelAPI_AttributeRefList::typeId()) {
761 AttributeRefListPtr aRefListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
762 aHasObject = aRefListAttr->isInList(theObject);
763 //if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
764 // aRefListAttr->append(theObject);
766 else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
767 AttributeRefAttrListPtr aRefAttrListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
768 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
770 if (anAttribute.get()) {
771 aHasObject = aRefAttrListAttr->isInList(anAttribute);
772 //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
773 // aRefAttrListAttr->append(anAttribute);
776 aHasObject = aRefAttrListAttr->isInList(theObject);
777 //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
778 // aRefAttrListAttr->append(theObject);
784 void setObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
785 const GeomShapePtr& theShape, ModuleBase_IWorkshop* theWorkshop,
786 const bool theTemporarily, const bool theCheckIfAttributeHasObject)
788 if (!theAttribute.get())
791 std::string aType = theAttribute->attributeType();
792 if (aType == ModelAPI_AttributeReference::typeId()) {
793 AttributeReferencePtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
794 ObjectPtr aObject = aRef->value();
795 if (!(aObject && aObject->isSame(theObject))) {
796 aRef->setValue(theObject);
798 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
799 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
801 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
802 if (anAttribute.get())
803 aRefAttr->setAttr(anAttribute);
805 ObjectPtr aObject = aRefAttr->object();
806 if (!(aObject && aObject->isSame(theObject))) {
807 aRefAttr->setObject(theObject);
810 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
811 AttributeSelectionPtr aSelectAttr =
812 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
813 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
814 if (aSelectAttr.get() != NULL) {
815 aSelectAttr->setValue(aResult, theShape, theTemporarily);
818 if (aType == ModelAPI_AttributeSelectionList::typeId()) {
819 AttributeSelectionListPtr aSelectionListAttr =
820 std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
821 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
822 if (!theCheckIfAttributeHasObject || !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
823 aSelectionListAttr->append(aResult, theShape, theTemporarily);
825 else if (aType == ModelAPI_AttributeRefList::typeId()) {
826 AttributeRefListPtr aRefListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
827 if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
828 aRefListAttr->append(theObject);
830 else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
831 AttributeRefAttrListPtr aRefAttrListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
832 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
834 if (anAttribute.get()) {
835 if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
836 aRefAttrListAttr->append(anAttribute);
839 if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
840 aRefAttrListAttr->append(theObject);
845 GeomShapePtr getShape(const AttributePtr& theAttribute, ModuleBase_IWorkshop* theWorkshop)
848 if (!theAttribute.get())
851 std::string aType = theAttribute->attributeType();
852 if (aType == ModelAPI_AttributeReference::typeId()) {
853 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
854 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
855 if (aRefAttr.get() && !aRefAttr->isObject()) {
856 AttributePtr anAttribute = aRefAttr->attr();
857 aShape = theWorkshop->module()->findShape(anAttribute);
859 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
860 AttributeSelectionPtr aSelectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>
862 aShape = aSelectAttr->value();
864 else // Geom2D point processing
865 aShape = theWorkshop->module()->findShape(theAttribute);
869 void flushUpdated(ObjectPtr theObject)
871 blockUpdateViewer(true);
873 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
875 blockUpdateViewer(false);
878 void blockUpdateViewer(const bool theValue)
880 // the viewer update should be blocked in order to avoid the temporary feature content
881 // when the solver processes the feature, the redisplay message can be flushed
882 // what caused the display in the viewer preliminary states of object
883 // e.g. fillet feature, angle value change
884 std::shared_ptr<Events_Message> aMsg;
886 aMsg = std::shared_ptr<Events_Message>(
887 new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)));
890 // the viewer update should be unblocked
891 aMsg = std::shared_ptr<Events_Message>(
892 new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)));
894 Events_Loop::loop()->send(aMsg);
897 QString wrapTextByWords(const QString& theValue, QWidget* theWidget,
898 int theMaxLineInPixels)
900 static QFontMetrics tfm(theWidget ? theWidget->font() : QApplication::font());
901 static qreal phi = 2.618;
903 QRect aBounds = tfm.boundingRect(theValue);
904 if(aBounds.width() <= theMaxLineInPixels)
907 qreal s = aBounds.width() * aBounds.height();
908 qreal aGoldWidth = sqrt(s*phi);
910 QStringList aWords = theValue.split(" ", QString::SkipEmptyParts);
912 int n = aWords.count();
914 for (int i = 0; i < n; i++) {
915 QString aLineExt = aLine + " " + aWords[i];
916 qreal anWidthNonExt = tfm.boundingRect(aLine).width();
917 qreal anWidthExt = tfm.boundingRect(aLineExt).width();
918 qreal aDeltaNonExt = fabs(anWidthNonExt-aGoldWidth);
919 qreal aDeltaExt = fabs(anWidthExt-aGoldWidth);
920 if(aDeltaNonExt < aDeltaExt) {
922 aLines.append(aLine);
930 aLines.append(aLine);
932 QString aResult = aLines.join("\n");
936 //**************************************************************
937 void refsToFeatureInFeatureDocument(const ObjectPtr& theObject, std::set<FeaturePtr>& theRefFeatures)
939 FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
940 if (aFeature.get()) {
941 DocumentPtr aFeatureDoc = aFeature->document();
942 // 1. find references in the current document
943 aFeatureDoc->refsToFeature(aFeature, theRefFeatures, false);
948 //**************************************************************
949 /*bool isSubOfComposite(const ObjectPtr& theObject)
952 std::set<FeaturePtr> aRefFeatures;
953 refsToFeatureInFeatureDocument(theObject, aRefFeatures);
954 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
955 aLast = aRefFeatures.end();
956 for (; anIt != aLast && !isSub; anIt++) {
957 isSub = isSubOfComposite(theObject, *anIt);
962 //**************************************************************
963 /*bool isSubOfComposite(const ObjectPtr& theObject, const FeaturePtr& theFeature)
966 CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
967 if (aComposite.get()) {
968 isSub = aComposite->isSub(theObject);
969 // the recursive is possible, the parameters are sketch circle and extrusion cut. They are
970 // separated by composite sketch feature
972 int aNbSubs = aComposite->numberOfSubs();
973 for (int aSub = 0; aSub < aNbSubs && !isSub; aSub++) {
974 isSub = isSubOfComposite(theObject, aComposite->subFeature(aSub));
981 //**************************************************************
982 ResultPtr firstResult(const ObjectPtr& theObject)
984 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
985 if (!aResult.get()) {
986 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
988 aResult = aFeature->firstResult();
993 //**************************************************************
994 bool isFeatureOfResult(const FeaturePtr& theFeature, const std::string& theGroupOfResult)
996 bool isResult = false;
998 if (!theFeature->data()->isValid())
1001 ResultPtr aFirstResult = theFeature->firstResult();
1002 if (!aFirstResult.get())
1005 return aFirstResult->groupName() == theGroupOfResult;
1008 //**************************************************************
1009 bool hasModuleDocumentFeature(const std::set<FeaturePtr>& theFeatures)
1011 bool aFoundModuleDocumentObject = false;
1012 DocumentPtr aModuleDoc = ModelAPI_Session::get()->moduleDocument();
1014 std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(), aLast = theFeatures.end();
1015 for (; anIt != aLast && !aFoundModuleDocumentObject; anIt++) {
1016 FeaturePtr aFeature = *anIt;
1017 ResultPtr aResult = ModuleBase_Tools::firstResult(aFeature);
1018 if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group())
1020 aFoundModuleDocumentObject = aFeature->document() == aModuleDoc;
1023 return aFoundModuleDocumentObject;
1026 //**************************************************************
1027 bool askToDelete(const std::set<FeaturePtr> theFeatures,
1028 const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
1030 std::set<FeaturePtr>& theReferencesToDelete)
1032 QString aNotActivatedDocWrn;
1033 std::string aNotActivatedNames;
1034 if (!ModelAPI_Tools::allDocumentsActivated(aNotActivatedNames)) {
1035 if (ModuleBase_Tools::hasModuleDocumentFeature(theFeatures))
1036 aNotActivatedDocWrn = QObject::tr("Selected objects can be used in Part documents which are not loaded:%1.\n")
1037 .arg(aNotActivatedNames.c_str());
1040 std::set<FeaturePtr> aFeaturesRefsTo;
1041 std::set<FeaturePtr> aFeaturesRefsToParameter;
1042 std::set<FeaturePtr> aParameterFeatures;
1043 QStringList aPartFeatureNames;
1044 std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
1045 aLast = theFeatures.end();
1046 // separate features to references to parameter features and references to others
1047 for (; anIt != aLast; anIt++) {
1048 FeaturePtr aFeature = *anIt;
1049 if (theReferences.find(aFeature) == theReferences.end())
1052 if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
1053 aPartFeatureNames.append(aFeature->name().c_str());
1055 std::set<FeaturePtr> aRefFeatures;
1056 std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
1057 std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
1058 for (; aRefIt != aRefLast; aRefIt++) {
1059 FeaturePtr aRefFeature = *aRefIt;
1060 if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
1061 aRefFeatures.find(aRefFeature) == aRefFeatures.end()) // it is not added
1062 aRefFeatures.insert(aRefFeature);
1065 if (isFeatureOfResult(aFeature, ModelAPI_ResultParameter::group())) {
1066 aFeaturesRefsToParameter.insert(aRefFeatures.begin(), aRefFeatures.end());
1067 aParameterFeatures.insert(aFeature);
1070 theReferencesToDelete.insert(aRefFeatures.begin(), aRefFeatures.end());
1074 std::set<FeaturePtr> aFeaturesRefsToParameterOnly;
1075 anIt = aFeaturesRefsToParameter.begin();
1076 aLast = aFeaturesRefsToParameter.end();
1077 // separate features to references to parameter features and references to others
1078 QStringList aParamFeatureNames;
1079 for (; anIt != aLast; anIt++) {
1080 FeaturePtr aFeature = *anIt;
1081 if (theReferencesToDelete.find(aFeature) == theReferencesToDelete.end()) {
1082 aFeaturesRefsToParameterOnly.insert(aFeature);
1083 aParamFeatureNames.append(aFeature->name().c_str());
1086 aParamFeatureNames.sort();
1087 QStringList anOtherFeatureNames;
1088 anIt = theReferencesToDelete.begin();
1089 aLast = theReferencesToDelete.end();
1090 for (; anIt != aLast; anIt++) {
1091 FeaturePtr aFeature = *anIt;
1092 if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
1093 aPartFeatureNames.append(aFeature->name().c_str());
1095 anOtherFeatureNames.append(aFeature->name().c_str());
1097 aPartFeatureNames.sort();
1098 anOtherFeatureNames.sort();
1100 bool aCanReplaceParameters = !aFeaturesRefsToParameterOnly.empty();
1102 QMessageBox aMessageBox(theParent);
1103 aMessageBox.setWindowTitle(QObject::tr("Delete features"));
1104 aMessageBox.setIcon(QMessageBox::Warning);
1105 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1106 aMessageBox.setDefaultButton(QMessageBox::No);
1109 QString aSep = ", ";
1110 if (!aPartFeatureNames.empty())
1111 aText += QString(QObject::tr("The following parts will be deleted: %1.\n")).arg(aPartFeatureNames.join(aSep));
1112 if (!aNotActivatedDocWrn.isEmpty())
1113 aText += aNotActivatedDocWrn;
1114 if (!anOtherFeatureNames.empty())
1115 aText += QString(QObject::tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n"))
1116 .arg(anOtherFeatureNames.join(aSep));
1117 if (!aParamFeatureNames.empty()) {
1118 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"))
1119 .arg(aParamFeatureNames.join(aSep));
1120 QPushButton *aReplaceButton = aMessageBox.addButton(QObject::tr("Replace"), QMessageBox::ActionRole);
1123 if (!aText.isEmpty()) {
1124 aText += "Would you like to continue?";
1125 aMessageBox.setText(aText);
1127 QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1129 if (aButtonRole == QMessageBox::NoRole)
1132 if (aButtonRole == QMessageBox::ActionRole) {
1133 foreach (FeaturePtr aObj, aParameterFeatures)
1134 ModelAPI_ReplaceParameterMessage::send(aObj, 0);
1137 theReferencesToDelete.insert(aFeaturesRefsToParameterOnly.begin(), aFeaturesRefsToParameterOnly.end());
1142 //**************************************************************
1143 void convertToFeatures(const QObjectPtrList& theObjects, std::set<FeaturePtr>& theFeatures)
1145 QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1146 for(; anIt != aLast; anIt++) {
1147 ObjectPtr anObject = *anIt;
1148 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1149 // for parameter result, use the corresponded reature to be removed
1150 if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1151 aFeature = ModelAPI_Feature::feature(anObject);
1153 theFeatures.insert(aFeature);
1157 void translate(const std::string& theContext, std::string& theMessage)
1159 if (!theMessage.empty()) {
1160 std::string aStr = Config_Translator::translate(theContext, theMessage);
1161 if (!aStr.empty()) {
1162 std::string aCodec = Config_Translator::codec(theContext);
1163 theMessage = QTextCodec::codecForName(aCodec.c_str())->toUnicode(aStr.c_str()).toStdString();
1168 void setPointBallHighlighting(AIS_Shape* theAIS)
1170 static Handle(Image_AlienPixMap) aPixMap;
1171 if(aPixMap.IsNull()) {
1172 // Load icon for the presentation
1174 char* anEnv = getenv("SHAPER_ROOT_DIR");
1176 aFile = std::string(anEnv) +
1177 FSEP + "share" + FSEP + "salome" + FSEP + "resources" + FSEP + "shaper";
1179 anEnv = getenv("OPENPARTS_ROOT_DIR");
1181 aFile = std::string(anEnv) + FSEP + "resources";
1185 static const std::string aMarkerName = "marker_dot.png";
1186 aFile += aMarkerName;
1187 aPixMap = new Image_AlienPixMap();
1188 if(!aPixMap->Load(aFile.c_str())) {
1189 // The icon for constraint is not found
1190 static const std::string aMsg = "Error: Point market not found by path: \"" + aFile + "\". Falling back.";
1191 //Events_InfoMessage("ModuleBase_Tools::setPointBallHighlighting", aMsg).send();
1195 Handle(Graphic3d_AspectMarker3d) anAspect;
1196 Handle(Prs3d_Drawer) aDrawer = theAIS->HilightAttributes();
1197 if(aDrawer->HasOwnPointAspect()) {
1198 Handle(Prs3d_PointAspect) aPntAspect = aDrawer->PointAspect();
1199 if(aPixMap->IsEmpty()) {
1200 anAspect = aPntAspect->Aspect();
1201 anAspect->SetType(Aspect_TOM_BALL);
1203 if(aPixMap->Format() == Image_PixMap::ImgGray) {
1204 aPixMap->SetFormat (Image_PixMap::ImgAlpha);
1205 } else if(aPixMap->Format() == Image_PixMap::ImgGrayF) {
1206 aPixMap->SetFormat (Image_PixMap::ImgAlphaF);
1208 anAspect = new Graphic3d_AspectMarker3d(aPixMap);
1209 aPntAspect->SetAspect(anAspect);
1211 aDrawer->SetPointAspect(aPntAspect);
1212 theAIS->SetHilightAttributes(aDrawer);
1216 } // namespace ModuleBase_Tools