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>
15 #include <ModuleBase_ResultPrs.h>
17 #include <ModelAPI_Attribute.h>
18 #include <ModelAPI_AttributeRefAttr.h>
19 #include <ModelAPI_AttributeReference.h>
20 #include <ModelAPI_AttributeSelection.h>
21 #include <ModelAPI_AttributeSelectionList.h>
22 #include <ModelAPI_AttributeRefList.h>
23 #include <ModelAPI_AttributeRefAttrList.h>
24 #include <ModelAPI_ResultPart.h>
25 #include <ModelAPI_ResultConstruction.h>
26 #include <Events_Loop.h>
28 #include <ModelAPI_Data.h>
29 #include <ModelAPI_Result.h>
30 #include <ModelAPI_ResultCompSolid.h>
31 #include <ModelAPI_ResultParameter.h>
32 #include <ModelAPI_Tools.h>
33 #include <ModelAPI_Session.h>
34 #include <ModelAPI_Events.h>
36 #include <TopoDS_Iterator.hxx>
38 #include <GeomDataAPI_Point2D.h>
39 #include <Events_InfoMessage.h>
40 #include <GeomAPI_ShapeExplorer.h>
42 #include <Config_PropManager.h>
43 #include <Config_Translator.h>
45 #include <Prs3d_PointAspect.hxx>
46 #include <Graphic3d_AspectMarker3d.hxx>
48 #include <Image_AlienPixMap.hxx>
54 #include <QDoubleSpinBox>
55 #include <QGraphicsDropShadowEffect>
57 #include <QApplication>
58 #include <QMessageBox>
65 const double tolerance = 1e-7;
66 const double DEFAULT_DEVIATION_COEFFICIENT = 1.e-4;
68 //#define DEBUG_ACTIVATE_WINDOW
69 //#define DEBUG_SET_FOCUS
70 //#define DEBUG_SELECTION_INFO
72 #ifdef DEBUG_SELECTION_INFO
73 #include <ModuleBase_ISelection.h>
74 #include <ModuleBase_ViewerPrs.h>
76 #include <AIS_InteractiveContext.hxx>
77 #include <AIS_ListOfInteractive.hxx>
78 #include <AIS_ListIteratorOfListOfInteractive.hxx>
79 #include <AIS_Shape.hxx>
80 #include <TopoDS_Shape.hxx>
81 #include <AIS_LocalContext.hxx>
82 #include <NCollection_List.hxx>
83 #include <StdSelect_BRepOwner.hxx>
84 #include <TColStd_ListOfInteger.hxx>
85 #include <TColStd_ListIteratorOfListOfInteger.hxx>
94 namespace ModuleBase_Tools {
96 //******************************************************************
98 //******************************************************************
100 void adjustMargins(QWidget* theWidget)
104 adjustMargins(theWidget->layout());
107 void adjustMargins(QLayout* theLayout)
111 theLayout->setContentsMargins(2, 5, 2, 5);
112 theLayout->setSpacing(4);
115 void zeroMargins(QWidget* theWidget)
119 zeroMargins(theWidget->layout());
122 void zeroMargins(QLayout* theLayout)
126 theLayout->setContentsMargins(0, 0, 0, 0);
127 theLayout->setSpacing(5);
130 void activateWindow(QWidget* theWidget, const QString& theInfo)
132 theWidget->activateWindow();
134 #ifdef DEBUG_ACTIVATE_WINDOW
135 qDebug(QString("activateWindow: %1").arg(theInfo).toStdString().c_str());
139 void setFocus(QWidget* theWidget, const QString& theInfo)
141 theWidget->setFocus();
143 #ifdef DEBUG_SET_FOCUS
144 qDebug(QString("setFocus: %1").arg(theInfo).toStdString().c_str());
148 void setShadowEffect(QWidget* theWidget, const bool isSetEffect)
151 QGraphicsDropShadowEffect* aGlowEffect = new QGraphicsDropShadowEffect();
152 aGlowEffect->setOffset(.0);
153 aGlowEffect->setBlurRadius(10.0);
154 aGlowEffect->setColor(QColor(0, 170, 255)); // Light-blue color, #00AAFF
155 theWidget->setGraphicsEffect(aGlowEffect);
158 QGraphicsEffect* anEffect = theWidget->graphicsEffect();
160 anEffect->deleteLater();
161 theWidget->setGraphicsEffect(NULL);
165 QPixmap composite(const QString& theAdditionalIcon, const QString& theIcon)
167 QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
168 QImage anAditional(theAdditionalIcon);
173 int anAddWidth = anAditional.width();
174 int anAddHeight = anAditional.height();
176 int aWidth = anIcon.width();
177 int aHeight = anIcon.height();
179 int aStartWidthPos = aWidth - anAddWidth - 1;
180 int aStartHeightPos = aHeight - anAddHeight - 1;
182 for (int i = 0; i < anAddWidth && i + aStartWidthPos < aWidth; i++)
184 for (int j = 0; j < anAddHeight && j + aStartHeightPos < aHeight; j++)
186 if (qAlpha(anAditional.pixel(i, j)) > 0)
187 anIcon.setPixel(i + aStartWidthPos, j + aStartHeightPos, anAditional.pixel(i, j));
190 return QPixmap::fromImage(anIcon);
193 QPixmap lighter(const QString& theIcon, const int theLighterValue)
195 QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
199 QImage aResult = ModuleBase_IconFactory::loadImage(theIcon);
200 for (int i = 0; i < anIcon.width(); i++)
202 for (int j = 0; j < anIcon.height(); j++)
204 QRgb anRgb = anIcon.pixel(i, j);
205 QColor aPixelColor(qRed(anRgb), qGreen(anRgb), qBlue(anRgb),
206 qAlpha(aResult.pixel(i, j)));
208 QColor aLighterColor = aPixelColor.lighter(theLighterValue);
209 aResult.setPixel(i, j, qRgba(aLighterColor.red(), aLighterColor.green(),
210 aLighterColor.blue(), aLighterColor.alpha()));
213 return QPixmap::fromImage(aResult);
216 void setSpinText(ModuleBase_ParamSpinBox* theSpin, const QString& theText)
218 if (theSpin->text() == theText)
220 // In order to avoid extra text setting because it will
221 // reset cursor position in control
222 bool isBlocked = theSpin->blockSignals(true);
223 theSpin->setText(theText);
224 theSpin->blockSignals(isBlocked);
227 void setSpinValue(QDoubleSpinBox* 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 setSpinValue(ModuleBase_ParamSpinBox* theSpin, double theValue)
238 if (fabs(theSpin->value() - theValue) < tolerance)
240 bool isBlocked = theSpin->blockSignals(true);
241 theSpin->setValue(theValue);
242 theSpin->blockSignals(isBlocked);
245 void setSpinText(ModuleBase_ParamIntSpinBox* theSpin, const QString& theText)
247 // In order to avoid extra text setting because it will
248 // reset cursor position in control
249 if (theSpin->text() == theText)
251 bool isBlocked = theSpin->blockSignals(true);
252 theSpin->setText(theText);
253 theSpin->blockSignals(isBlocked);
256 void setSpinValue(ModuleBase_ParamIntSpinBox* theSpin, int theValue)
258 if (theSpin->value() == theValue)
260 bool isBlocked = theSpin->blockSignals(true);
261 theSpin->setValue(theValue);
262 theSpin->blockSignals(isBlocked);
265 QAction* createAction(const QIcon& theIcon, const QString& theText,
266 QObject* theParent, const QObject* theReceiver,
267 const char* theMember, const QString& theToolTip,
268 const QString& theStatusTip)
270 QAction* anAction = new QAction(theIcon, theText, theParent);
271 anAction->setToolTip(theToolTip.isEmpty() ? theText : theToolTip);
272 anAction->setStatusTip(!theStatusTip.isEmpty() ? theStatusTip :
273 (!theToolTip.isEmpty() ? theToolTip : theText));
275 QObject::connect(anAction, SIGNAL(triggered(bool)), theReceiver, theMember);
280 QString objectInfo(const ObjectPtr& theObj, const bool isUseAttributesInfo)
282 QString aFeatureStr = "feature";
286 std::ostringstream aPtrStr;
287 aPtrStr << "[" << theObj.get() << "]";
289 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theObj);
290 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
292 aFeatureStr.append(QString("(result%1)").arg(aPtrStr.str().c_str()).toStdString() .c_str());
293 if (aRes->isDisabled())
294 aFeatureStr.append("[disabled]");
295 if (aRes->isConcealed())
296 aFeatureStr.append("[concealed]");
297 if (ModelAPI_Tools::hasSubResults(aRes))
298 aFeatureStr.append("[hasSubResults]");
300 aFeature = ModelAPI_Feature::feature(aRes);
303 aFeatureStr.append(aPtrStr.str().c_str());
305 if (aFeature.get()) {
306 aFeatureStr.append(QString(": %1").arg(aFeature->getKind().c_str()).toStdString().c_str());
307 if (aFeature->data()->isValid()) {
308 aFeatureStr.append(QString(", name=%1").arg(theObj->data()->name().c_str()).toStdString()
311 if (isUseAttributesInfo) {
312 std::list<AttributePtr> anAttrs = aFeature->data()->attributes("");
313 std::list<AttributePtr>::const_iterator anIt = anAttrs.begin(), aLast = anAttrs.end();
315 for(; anIt != aLast; anIt++) {
316 AttributePtr anAttr = *anIt;
317 QString aValue = "not defined";
318 std::string aType = anAttr->attributeType();
319 if (aType == GeomDataAPI_Point2D::typeId()) {
320 std::shared_ptr<GeomDataAPI_Point2D> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
323 aValue = QString("(%1, %2)").arg(aPoint->x()).arg(aPoint->y());
325 else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
328 aValues.push_back(QString("%1: %2").arg(anAttr->id().c_str()).arg(aValue).toStdString().c_str());
330 if (!aValues.empty())
331 aFeatureStr.append(QString(", attributes: %1").arg(aValues.join(", ").toStdString().c_str()));
338 #ifdef DEBUG_SELECTION_INFO
339 QString getShapeTypeInfo(const int theType)
341 QString anInfo = "Undefined";
343 case TopAbs_COMPOUND: anInfo = "compound"; break;
344 case TopAbs_COMPSOLID: anInfo = "compsolid"; break;
345 case TopAbs_SOLID: anInfo = "solid"; break;
346 case TopAbs_SHELL: anInfo = "shell"; break;
347 case TopAbs_FACE: anInfo = "face"; break;
348 case TopAbs_WIRE: anInfo = "wire"; break;
349 case TopAbs_EDGE: anInfo = "edge"; break;
350 case TopAbs_VERTEX: anInfo = "vertex"; break;
351 case TopAbs_SHAPE: anInfo = "shape"; break;
352 case ModuleBase_ResultPrs::Sel_Result:
353 anInfo = "result_shape"; break;
359 QString getModeInfo(const int theMode)
361 QString anInfo = "Undefined";
363 case 0: anInfo = "SHAPE(0)"; break;
364 case 1: anInfo = "VERTEX(1)"; break;
365 case 2: anInfo = "EDGE(2)"; break;
366 case 3: anInfo = "WIRE(3)"; break;
367 case 4: anInfo = "FACE(4)"; break;
368 case 5: anInfo = "SHELL(5)"; break;
369 case 6: anInfo = "SOLID(6)"; break;
370 case 7: anInfo = "COMPSOLID(7)"; break;
371 case 8: anInfo = "COMPOUND(8)"; break;
372 case 100: anInfo = "Sel_Mode_First(100)"; break; //SketcherPrs_Tools
373 case 101: anInfo = "Sel_Constraint(101)"; break;
374 case 102: anInfo = "Sel_Dimension_All(102)"; break;
375 case 103: anInfo = "Sel_Dimension_Line(103)"; break;
376 case 104: anInfo = "Sel_Dimension_Text(104)"; break;
382 QString displayedInteractiveObjects(Handle(AIS_InteractiveContext)& theContext,
383 const bool theShapeInfoOnly = true)
385 if (theContext.IsNull())
387 AIS_ListOfInteractive aListOfIO;
388 theContext->DisplayedObjects(aListOfIO, false);
389 QStringList anObjects;
390 AIS_ListIteratorOfListOfInteractive aIt;
391 for (aIt.Initialize(aListOfIO); aIt.More(); aIt.Next()) {
392 Handle(AIS_InteractiveObject) anAISIO = aIt.Value();
393 Handle(AIS_Shape) aShapePrs = Handle(AIS_Shape)::DownCast(anAISIO);
394 if (theShapeInfoOnly && aShapePrs.IsNull())
397 QString anInfo = "IO";
398 std::ostringstream aPtrStr;
399 aPtrStr << "[" << anAISIO.Access() << "]";
400 anInfo += aPtrStr.str().c_str();
402 if (!aShapePrs.IsNull()) {
403 const TopoDS_Shape& aShape = aShapePrs->Shape();
404 if (aShape.IsNull()) {
405 //Events_Error::throwException("An empty AIS presentation");
408 anInfo += QString(", shape type: %1").arg(getShapeTypeInfo(aShape.ShapeType()));
410 TColStd_ListOfInteger aTColModes;
411 theContext->ActivatedModes(anAISIO, aTColModes);
412 TColStd_ListIteratorOfListOfInteger itr( aTColModes );
413 QIntList aModesActivatedForIO;
414 bool isDeactivated = false;
416 for (; itr.More(); itr.Next() ) {
417 Standard_Integer aMode = itr.Value();
418 aModes.append(getModeInfo(aMode));
419 //int aShapeMode = (aMode > 8)? aMode : AIS_Shape::SelectionType(aMode);
421 if (aModes.size() > 0)
422 anInfo += QString(", activated modes: %1").arg(aModes.join(", "));
426 QString aValue = QString("displayedIO[%1]").arg(anObjects.size());
427 if (anObjects.size() > 0)
428 aValue += QString(":\n %1").arg(anObjects.join("\n "));
432 QString activeOwners(Handle(AIS_InteractiveContext)& theContext, const bool theShapeInfoOnly = true)
434 if (theContext.IsNull())
436 Handle(AIS_LocalContext) aLContext = theContext->LocalContext();
437 TCollection_AsciiString aSelectionName = aLContext->SelectionName();
438 aLContext->UnhilightPicked(Standard_False);
440 NCollection_List<Handle(SelectBasics_EntityOwner)> anActiveOwners;
441 aLContext->MainSelector()->ActiveOwners(anActiveOwners);
442 NCollection_List<Handle(SelectBasics_EntityOwner)>::Iterator anOwnersIt (anActiveOwners);
443 Handle(SelectMgr_EntityOwner) anOwner;
444 QStringList anObjects;
445 for (; anOwnersIt.More(); anOwnersIt.Next()) {
446 anOwner = Handle(SelectMgr_EntityOwner)::DownCast (anOwnersIt.Value());
447 Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
448 if (theShapeInfoOnly && BROwnr.IsNull())
451 QString anInfo = "Owner";
452 std::ostringstream aPtrStr;
453 aPtrStr << "[" << anOwner.Access() << "]";
454 anInfo += aPtrStr.str().c_str();
456 Handle(AIS_InteractiveObject) aAISObj =
457 Handle(AIS_InteractiveObject)::DownCast(anOwner->Selectable());
458 if (!aAISObj.IsNull()) {
459 std::ostringstream aPtrStr;
460 aPtrStr << "[" << aAISObj.Access() << "]";
461 anInfo += QString(", selectable(IO): %1").arg(aPtrStr.str().c_str());
464 if (!BROwnr.IsNull() && BROwnr->HasShape()) {
465 const TopoDS_Shape& aShape = BROwnr->Shape();
466 if (aShape.IsNull()) {
467 //Events_Error::throwException("An empty AIS presentation");
470 anInfo += QString(", shape type: %1").arg(getShapeTypeInfo(aShape.ShapeType()));
474 QString aValue = QString("activeOwners[%1]").arg(anObjects.size());
475 if (anObjects.size() > 0)
476 aValue += QString(":\n %1").arg(anObjects.join("\n "));
480 QString selectedOwners(Handle(AIS_InteractiveContext)& theContext, const bool theShapeInfoOnly = true)
482 QStringList anObjects;
483 if (theContext.IsNull())
486 QList<long> aSelectedIds; // Remember of selected address in order to avoid duplicates
487 for (theContext->InitSelected(); theContext->MoreSelected(); theContext->NextSelected()) {
488 Handle(SelectMgr_EntityOwner) anOwner = theContext->SelectedOwner();
489 Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
490 if (theShapeInfoOnly && BROwnr.IsNull())
493 if (aSelectedIds.contains((long)anOwner.Access()))
495 aSelectedIds.append((long)anOwner.Access());
497 QString anInfo = "Owner";
498 std::ostringstream aPtrStr;
499 aPtrStr << "[" << anOwner.Access() << "]";
500 anInfo += aPtrStr.str().c_str();
502 if (!BROwnr.IsNull() && BROwnr->HasShape()) {
503 const TopoDS_Shape& aShape = BROwnr->Shape();
504 anInfo += QString(", shape type = %1").arg(getShapeTypeInfo(aShape.ShapeType()));
508 QString aValue = QString("selectedOwners[%1]").arg(anObjects.size());
509 if (anObjects.size() > 0)
510 aValue += QString(":\n %1").arg(anObjects.join("\n "));
515 void selectionInfo(Handle(AIS_InteractiveContext)& theContext, const std::string& thePrefix)
517 #ifdef DEBUG_SELECTION_INFO
518 QString aValue = QString("\n\n\nDEBUG_SELECTION_INFO for '%1'\n%2\n%3\n%4")
519 .arg(thePrefix.c_str())
520 .arg(displayedInteractiveObjects(theContext))
521 .arg(activeOwners(theContext))
522 .arg(selectedOwners(theContext));
523 qDebug(aValue.toStdString().c_str());
527 typedef QMap<QString, int> ShapeTypes;
528 static ShapeTypes myShapeTypes;
530 int shapeType(const QString& theType)
532 if (myShapeTypes.count() == 0) {
533 myShapeTypes["compound"] = TopAbs_COMPOUND;
534 myShapeTypes["compounds"] = TopAbs_COMPOUND;
535 myShapeTypes["compsolid"] = TopAbs_COMPSOLID;
536 myShapeTypes["compsolids"] = TopAbs_COMPSOLID;
537 myShapeTypes["solid"] = TopAbs_SOLID;
538 myShapeTypes["solids"] = TopAbs_SOLID;
539 myShapeTypes["shell"] = TopAbs_SHELL;
540 myShapeTypes["shells"] = TopAbs_SHELL;
541 myShapeTypes["face"] = TopAbs_FACE;
542 myShapeTypes["faces"] = TopAbs_FACE;
543 myShapeTypes["wire"] = TopAbs_WIRE;
544 myShapeTypes["wires"] = TopAbs_WIRE;
545 myShapeTypes["edge"] = TopAbs_EDGE;
546 myShapeTypes["edges"] = TopAbs_EDGE;
547 myShapeTypes["vertex"] = TopAbs_VERTEX;
548 myShapeTypes["vertices"] = TopAbs_VERTEX;
549 myShapeTypes["object"] = ModuleBase_ResultPrs::Sel_Result;
550 myShapeTypes["objects"] = ModuleBase_ResultPrs::Sel_Result;
552 QString aType = theType.toLower();
553 if(myShapeTypes.contains(aType))
554 return myShapeTypes[aType];
555 Events_InfoMessage("ModuleBase_Tools", "Shape type defined in XML is not implemented!").send();
559 void checkObjects(const QObjectPtrList& theObjects, bool& hasResult, bool& hasFeature,
560 bool& hasParameter, bool& hasCompositeOwner)
564 hasParameter = false;
565 hasCompositeOwner = false;
566 foreach(ObjectPtr aObj, theObjects) {
567 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
568 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
569 ResultParameterPtr aConstruction = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aResult);
571 hasResult |= (aResult.get() != NULL);
572 hasFeature |= (aFeature.get() != NULL);
573 hasParameter |= (aConstruction.get() != NULL);
575 hasCompositeOwner |= (ModelAPI_Tools::compositeOwner(aFeature) != NULL);
576 if (hasFeature && hasResult && hasParameter && hasCompositeOwner)
581 bool setDefaultDeviationCoefficient(std::shared_ptr<GeomAPI_Shape> theGeomShape)
583 if (!theGeomShape.get())
585 // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
586 // correction of deviation for them should not influence to the application performance
587 GeomAPI_ShapeExplorer anExp(theGeomShape, GeomAPI_Shape::FACE);
588 bool anEmpty = anExp.empty();
589 return !anExp.more();
592 void setDefaultDeviationCoefficient(const std::shared_ptr<ModelAPI_Result>& theResult,
593 const Handle(Prs3d_Drawer)& theDrawer)
595 if (!theResult.get())
597 bool aUseDeviation = false;
599 std::string aResultGroup = theResult->groupName();
600 if (aResultGroup == ModelAPI_ResultConstruction::group())
601 aUseDeviation = true;
602 else if (aResultGroup == ModelAPI_ResultBody::group()) {
603 GeomShapePtr aGeomShape = theResult->shape();
604 if (aGeomShape.get())
605 aUseDeviation = setDefaultDeviationCoefficient(aGeomShape);
608 theDrawer->SetDeviationCoefficient(DEFAULT_DEVIATION_COEFFICIENT);
611 void setDefaultDeviationCoefficient(const TopoDS_Shape& theShape,
612 const Handle(Prs3d_Drawer)& theDrawer)
614 if (theShape.IsNull())
617 std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape());
618 aGeomShape->setImpl(new TopoDS_Shape(theShape));
619 if (setDefaultDeviationCoefficient(aGeomShape))
620 theDrawer->SetDeviationCoefficient(DEFAULT_DEVIATION_COEFFICIENT);
623 Quantity_Color color(const std::string& theSection,
624 const std::string& theName,
625 const std::string& theDefault)
627 std::vector<int> aColor = Config_PropManager::color(theSection, theName, theDefault);
628 return Quantity_Color(aColor[0] / 255., aColor[1] / 255., aColor[2] / 255., Quantity_TOC_RGB);
631 ObjectPtr getObject(const AttributePtr& theAttribute)
634 std::string anAttrType = theAttribute->attributeType();
635 if (anAttrType == ModelAPI_AttributeRefAttr::typeId()) {
636 AttributeRefAttrPtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
637 if (anAttr != NULL && anAttr->isObject())
638 anObject = anAttr->object();
640 if (anAttrType == ModelAPI_AttributeSelection::typeId()) {
641 AttributeSelectionPtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
643 anObject = anAttr->context();
645 if (anAttrType == ModelAPI_AttributeReference::typeId()) {
646 AttributeReferencePtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
647 if (anAttr.get() != NULL)
648 anObject = anAttr->value();
653 TopAbs_ShapeEnum getCompoundSubType(const TopoDS_Shape& theShape)
655 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
657 // for compounds check sub-shapes: it may be compound of needed type:
658 // Booleans may produce compounds of Solids
659 if (aShapeType == TopAbs_COMPOUND) {
660 for(TopoDS_Iterator aSubs(theShape); aSubs.More(); aSubs.Next()) {
661 if (!aSubs.Value().IsNull()) {
662 TopAbs_ShapeEnum aSubType = aSubs.Value().ShapeType();
663 if (aSubType == TopAbs_COMPOUND) { // compound of compound(s)
664 aShapeType = TopAbs_COMPOUND;
667 if (aShapeType == TopAbs_COMPOUND) {
668 aShapeType = aSubType;
669 } else if (aShapeType != aSubType) { // compound of shapes of different types
670 aShapeType = TopAbs_COMPOUND;
679 void getParameters(QStringList& theParameters)
681 theParameters.clear();
683 SessionPtr aSession = ModelAPI_Session::get();
684 std::list<DocumentPtr> aDocList;
685 DocumentPtr anActiveDocument = aSession->activeDocument();
686 DocumentPtr aRootDocument = aSession->moduleDocument();
687 aDocList.push_back(anActiveDocument);
688 if (anActiveDocument != aRootDocument) {
689 aDocList.push_back(aRootDocument);
691 std::string aGroupId = ModelAPI_ResultParameter::group();
692 for(std::list<DocumentPtr>::const_iterator it = aDocList.begin(); it != aDocList.end(); ++it) {
693 DocumentPtr aDocument = *it;
694 int aSize = aDocument->size(aGroupId);
695 for (int i = 0; i < aSize; i++) {
696 ObjectPtr anObject = aDocument->object(aGroupId, i);
697 std::string aParameterName = anObject->data()->name();
698 theParameters.append(aParameterName.c_str());
703 std::string findGreedAttribute(ModuleBase_IWorkshop* theWorkshop, const FeaturePtr& theFeature)
705 std::string anAttributeId;
707 std::string aXmlCfg, aDescription;
708 theWorkshop->module()->getXMLRepresentation(theFeature->getKind(), aXmlCfg, aDescription);
710 ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
711 std::string anAttributeTitle;
712 aFactory.getGreedAttribute(anAttributeId);
714 return anAttributeId;
717 bool hasObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
718 const std::shared_ptr<GeomAPI_Shape>& theShape,
719 ModuleBase_IWorkshop* theWorkshop,
720 const bool theTemporarily)
722 bool aHasObject = false;
723 if (!theAttribute.get())
726 std::string aType = theAttribute->attributeType();
727 if (aType == ModelAPI_AttributeReference::typeId()) {
728 AttributeReferencePtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
729 ObjectPtr aObject = aRef->value();
730 aHasObject = aObject && aObject->isSame(theObject);
731 //if (!(aObject && aObject->isSame(theObject))) {
732 // aRef->setValue(theObject);
734 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
735 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
737 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
738 if (anAttribute.get()) {
739 //aRefAttr->setAttr(anAttribute);
742 ObjectPtr aObject = aRefAttr->object();
743 aHasObject = aObject && aObject->isSame(theObject);
744 //if (!(aObject && aObject->isSame(theObject))) {
745 // aRefAttr->setObject(theObject);
748 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
749 /*AttributeSelectionPtr aSelectAttr =
750 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
751 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
752 if (aSelectAttr.get() != NULL) {
753 aSelectAttr->setValue(aResult, theShape, theTemporarily);
756 if (aType == ModelAPI_AttributeSelectionList::typeId()) {
757 AttributeSelectionListPtr aSelectionListAttr =
758 std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
759 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
760 aHasObject = aSelectionListAttr->isInList(aResult, theShape, theTemporarily);
761 //if (!theCheckIfAttributeHasObject || !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
762 // aSelectionListAttr->append(aResult, theShape, theTemporarily);
764 else if (aType == ModelAPI_AttributeRefList::typeId()) {
765 AttributeRefListPtr aRefListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
766 aHasObject = aRefListAttr->isInList(theObject);
767 //if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
768 // aRefListAttr->append(theObject);
770 else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
771 AttributeRefAttrListPtr aRefAttrListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
772 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
774 if (anAttribute.get()) {
775 aHasObject = aRefAttrListAttr->isInList(anAttribute);
776 //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
777 // aRefAttrListAttr->append(anAttribute);
780 aHasObject = aRefAttrListAttr->isInList(theObject);
781 //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
782 // aRefAttrListAttr->append(theObject);
788 void setObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
789 const GeomShapePtr& theShape, ModuleBase_IWorkshop* theWorkshop,
790 const bool theTemporarily, const bool theCheckIfAttributeHasObject)
792 if (!theAttribute.get())
795 std::string aType = theAttribute->attributeType();
796 if (aType == ModelAPI_AttributeReference::typeId()) {
797 AttributeReferencePtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
798 ObjectPtr aObject = aRef->value();
799 if (!(aObject && aObject->isSame(theObject))) {
800 aRef->setValue(theObject);
802 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
803 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
805 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
806 if (anAttribute.get())
807 aRefAttr->setAttr(anAttribute);
809 ObjectPtr aObject = aRefAttr->object();
810 if (!(aObject && aObject->isSame(theObject))) {
811 aRefAttr->setObject(theObject);
814 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
815 AttributeSelectionPtr aSelectAttr =
816 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
817 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
818 if (aSelectAttr.get() != NULL) {
819 aSelectAttr->setValue(aResult, theShape, theTemporarily);
822 if (aType == ModelAPI_AttributeSelectionList::typeId()) {
823 AttributeSelectionListPtr aSelectionListAttr =
824 std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
825 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
826 if (!theCheckIfAttributeHasObject || !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
827 aSelectionListAttr->append(aResult, theShape, theTemporarily);
829 else if (aType == ModelAPI_AttributeRefList::typeId()) {
830 AttributeRefListPtr aRefListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
831 if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
832 aRefListAttr->append(theObject);
834 else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
835 AttributeRefAttrListPtr aRefAttrListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
836 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
838 if (anAttribute.get()) {
839 if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
840 aRefAttrListAttr->append(anAttribute);
843 if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
844 aRefAttrListAttr->append(theObject);
849 GeomShapePtr getShape(const AttributePtr& theAttribute, ModuleBase_IWorkshop* theWorkshop)
852 if (!theAttribute.get())
855 std::string aType = theAttribute->attributeType();
856 if (aType == ModelAPI_AttributeReference::typeId()) {
857 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
858 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
859 if (aRefAttr.get() && !aRefAttr->isObject()) {
860 AttributePtr anAttribute = aRefAttr->attr();
861 aShape = theWorkshop->module()->findShape(anAttribute);
863 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
864 AttributeSelectionPtr aSelectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>
866 aShape = aSelectAttr->value();
868 else // Geom2D point processing
869 aShape = theWorkshop->module()->findShape(theAttribute);
873 void flushUpdated(ObjectPtr theObject)
875 blockUpdateViewer(true);
877 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
879 blockUpdateViewer(false);
882 void blockUpdateViewer(const bool theValue)
884 // the viewer update should be blocked in order to avoid the temporary feature content
885 // when the solver processes the feature, the redisplay message can be flushed
886 // what caused the display in the viewer preliminary states of object
887 // e.g. fillet feature, angle value change
888 std::shared_ptr<Events_Message> aMsg;
890 aMsg = std::shared_ptr<Events_Message>(
891 new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)));
894 // the viewer update should be unblocked
895 aMsg = std::shared_ptr<Events_Message>(
896 new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)));
898 Events_Loop::loop()->send(aMsg);
901 QString wrapTextByWords(const QString& theValue, QWidget* theWidget,
902 int theMaxLineInPixels)
904 static QFontMetrics tfm(theWidget ? theWidget->font() : QApplication::font());
905 static qreal phi = 2.618;
907 QRect aBounds = tfm.boundingRect(theValue);
908 if(aBounds.width() <= theMaxLineInPixels)
911 qreal s = aBounds.width() * aBounds.height();
912 qreal aGoldWidth = sqrt(s*phi);
914 QStringList aWords = theValue.split(" ", QString::SkipEmptyParts);
916 int n = aWords.count();
918 for (int i = 0; i < n; i++) {
919 QString aLineExt = aLine + " " + aWords[i];
920 qreal anWidthNonExt = tfm.boundingRect(aLine).width();
921 qreal anWidthExt = tfm.boundingRect(aLineExt).width();
922 qreal aDeltaNonExt = fabs(anWidthNonExt-aGoldWidth);
923 qreal aDeltaExt = fabs(anWidthExt-aGoldWidth);
924 if(aDeltaNonExt < aDeltaExt) {
926 aLines.append(aLine);
934 aLines.append(aLine);
936 QString aResult = aLines.join("\n");
940 //**************************************************************
941 void refsToFeatureInFeatureDocument(const ObjectPtr& theObject, std::set<FeaturePtr>& theRefFeatures)
943 FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
944 if (aFeature.get()) {
945 DocumentPtr aFeatureDoc = aFeature->document();
946 // 1. find references in the current document
947 aFeatureDoc->refsToFeature(aFeature, theRefFeatures, false);
952 //**************************************************************
953 /*bool isSubOfComposite(const ObjectPtr& theObject)
956 std::set<FeaturePtr> aRefFeatures;
957 refsToFeatureInFeatureDocument(theObject, aRefFeatures);
958 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
959 aLast = aRefFeatures.end();
960 for (; anIt != aLast && !isSub; anIt++) {
961 isSub = isSubOfComposite(theObject, *anIt);
966 //**************************************************************
967 /*bool isSubOfComposite(const ObjectPtr& theObject, const FeaturePtr& theFeature)
970 CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
971 if (aComposite.get()) {
972 isSub = aComposite->isSub(theObject);
973 // the recursive is possible, the parameters are sketch circle and extrusion cut. They are
974 // separated by composite sketch feature
976 int aNbSubs = aComposite->numberOfSubs();
977 for (int aSub = 0; aSub < aNbSubs && !isSub; aSub++) {
978 isSub = isSubOfComposite(theObject, aComposite->subFeature(aSub));
985 //**************************************************************
986 ResultPtr firstResult(const ObjectPtr& theObject)
988 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
989 if (!aResult.get()) {
990 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
992 aResult = aFeature->firstResult();
997 //**************************************************************
998 bool isFeatureOfResult(const FeaturePtr& theFeature, const std::string& theGroupOfResult)
1000 bool isResult = false;
1002 if (!theFeature->data()->isValid())
1005 ResultPtr aFirstResult = theFeature->firstResult();
1006 if (!aFirstResult.get())
1009 return aFirstResult->groupName() == theGroupOfResult;
1012 //**************************************************************
1013 bool hasModuleDocumentFeature(const std::set<FeaturePtr>& theFeatures)
1015 bool aFoundModuleDocumentObject = false;
1016 DocumentPtr aModuleDoc = ModelAPI_Session::get()->moduleDocument();
1018 std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(), aLast = theFeatures.end();
1019 for (; anIt != aLast && !aFoundModuleDocumentObject; anIt++) {
1020 FeaturePtr aFeature = *anIt;
1021 ResultPtr aResult = ModuleBase_Tools::firstResult(aFeature);
1022 if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group())
1024 aFoundModuleDocumentObject = aFeature->document() == aModuleDoc;
1027 return aFoundModuleDocumentObject;
1030 //**************************************************************
1031 bool askToDelete(const std::set<FeaturePtr> theFeatures,
1032 const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
1034 std::set<FeaturePtr>& theReferencesToDelete)
1036 QString aNotActivatedDocWrn;
1037 std::string aNotActivatedNames;
1038 if (!ModelAPI_Tools::allDocumentsActivated(aNotActivatedNames)) {
1039 if (ModuleBase_Tools::hasModuleDocumentFeature(theFeatures))
1040 aNotActivatedDocWrn = QObject::tr("Selected objects can be used in Part documents which are not loaded:%1.\n")
1041 .arg(aNotActivatedNames.c_str());
1044 std::set<FeaturePtr> aFeaturesRefsTo;
1045 std::set<FeaturePtr> aFeaturesRefsToParameter;
1046 std::set<FeaturePtr> aParameterFeatures;
1047 QStringList aPartFeatureNames;
1048 std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
1049 aLast = theFeatures.end();
1050 // separate features to references to parameter features and references to others
1051 for (; anIt != aLast; anIt++) {
1052 FeaturePtr aFeature = *anIt;
1053 if (theReferences.find(aFeature) == theReferences.end())
1056 if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
1057 aPartFeatureNames.append(aFeature->name().c_str());
1059 std::set<FeaturePtr> aRefFeatures;
1060 std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
1061 std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
1062 for (; aRefIt != aRefLast; aRefIt++) {
1063 FeaturePtr aRefFeature = *aRefIt;
1064 if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
1065 aRefFeatures.find(aRefFeature) == aRefFeatures.end()) // it is not added
1066 aRefFeatures.insert(aRefFeature);
1069 if (isFeatureOfResult(aFeature, ModelAPI_ResultParameter::group())) {
1070 aFeaturesRefsToParameter.insert(aRefFeatures.begin(), aRefFeatures.end());
1071 aParameterFeatures.insert(aFeature);
1074 theReferencesToDelete.insert(aRefFeatures.begin(), aRefFeatures.end());
1078 std::set<FeaturePtr> aFeaturesRefsToParameterOnly;
1079 anIt = aFeaturesRefsToParameter.begin();
1080 aLast = aFeaturesRefsToParameter.end();
1081 // separate features to references to parameter features and references to others
1082 QStringList aParamFeatureNames;
1083 for (; anIt != aLast; anIt++) {
1084 FeaturePtr aFeature = *anIt;
1085 if (theReferencesToDelete.find(aFeature) == theReferencesToDelete.end()) {
1086 aFeaturesRefsToParameterOnly.insert(aFeature);
1087 aParamFeatureNames.append(aFeature->name().c_str());
1090 aParamFeatureNames.sort();
1091 QStringList anOtherFeatureNames;
1092 anIt = theReferencesToDelete.begin();
1093 aLast = theReferencesToDelete.end();
1094 for (; anIt != aLast; anIt++) {
1095 FeaturePtr aFeature = *anIt;
1096 if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
1097 aPartFeatureNames.append(aFeature->name().c_str());
1099 anOtherFeatureNames.append(aFeature->name().c_str());
1101 aPartFeatureNames.sort();
1102 anOtherFeatureNames.sort();
1104 bool aCanReplaceParameters = !aFeaturesRefsToParameterOnly.empty();
1106 QMessageBox aMessageBox(theParent);
1107 aMessageBox.setWindowTitle(QObject::tr("Delete features"));
1108 aMessageBox.setIcon(QMessageBox::Warning);
1109 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1110 aMessageBox.setDefaultButton(QMessageBox::No);
1113 QString aSep = ", ";
1114 if (!aPartFeatureNames.empty())
1115 aText += QString(QObject::tr("The following parts will be deleted: %1.\n")).arg(aPartFeatureNames.join(aSep));
1116 if (!aNotActivatedDocWrn.isEmpty())
1117 aText += aNotActivatedDocWrn;
1118 if (!anOtherFeatureNames.empty())
1119 aText += QString(QObject::tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n"))
1120 .arg(anOtherFeatureNames.join(aSep));
1121 if (!aParamFeatureNames.empty()) {
1122 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"))
1123 .arg(aParamFeatureNames.join(aSep));
1124 QPushButton *aReplaceButton = aMessageBox.addButton(QObject::tr("Replace"), QMessageBox::ActionRole);
1127 if (!aText.isEmpty()) {
1128 aText += "Would you like to continue?";
1129 aMessageBox.setText(aText);
1131 QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1133 if (aButtonRole == QMessageBox::NoRole)
1136 if (aButtonRole == QMessageBox::ActionRole) {
1137 foreach (FeaturePtr aObj, aParameterFeatures)
1138 ModelAPI_ReplaceParameterMessage::send(aObj, 0);
1141 theReferencesToDelete.insert(aFeaturesRefsToParameterOnly.begin(), aFeaturesRefsToParameterOnly.end());
1146 //**************************************************************
1147 void convertToFeatures(const QObjectPtrList& theObjects, std::set<FeaturePtr>& theFeatures)
1149 QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1150 for(; anIt != aLast; anIt++) {
1151 ObjectPtr anObject = *anIt;
1152 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1153 // for parameter result, use the corresponded reature to be removed
1154 if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1155 aFeature = ModelAPI_Feature::feature(anObject);
1157 theFeatures.insert(aFeature);
1161 void translate(const std::string& theContext, std::string& theMessage)
1163 if (!theMessage.empty()) {
1164 std::string aStr = Config_Translator::translate(theContext, theMessage);
1165 if (!aStr.empty()) {
1166 std::string aCodec = Config_Translator::codec(theContext);
1167 theMessage = QTextCodec::codecForName(aCodec.c_str())->toUnicode(aStr.c_str()).toStdString();
1172 void setPointBallHighlighting(AIS_Shape* theAIS)
1174 static Handle(Image_AlienPixMap) aPixMap;
1175 if(aPixMap.IsNull()) {
1176 // Load icon for the presentation
1178 char* anEnv = getenv("SHAPER_ROOT_DIR");
1180 aFile = std::string(anEnv) +
1181 FSEP + "share" + FSEP + "salome" + FSEP + "resources" + FSEP + "shaper";
1183 anEnv = getenv("OPENPARTS_ROOT_DIR");
1185 aFile = std::string(anEnv) + FSEP + "resources";
1189 static const std::string aMarkerName = "marker_dot.png";
1190 aFile += aMarkerName;
1191 aPixMap = new Image_AlienPixMap();
1192 if(!aPixMap->Load(aFile.c_str())) {
1193 // The icon for constraint is not found
1194 static const std::string aMsg = "Error: Point market not found by path: \"" + aFile + "\". Falling back.";
1195 //Events_InfoMessage("ModuleBase_Tools::setPointBallHighlighting", aMsg).send();
1199 Handle(Graphic3d_AspectMarker3d) anAspect;
1200 Handle(Prs3d_Drawer) aDrawer = theAIS->HilightAttributes();
1201 if(aDrawer->HasOwnPointAspect()) {
1202 Handle(Prs3d_PointAspect) aPntAspect = aDrawer->PointAspect();
1203 if(aPixMap->IsEmpty()) {
1204 anAspect = aPntAspect->Aspect();
1205 anAspect->SetType(Aspect_TOM_BALL);
1207 if(aPixMap->Format() == Image_PixMap::ImgGray) {
1208 aPixMap->SetFormat (Image_PixMap::ImgAlpha);
1209 } else if(aPixMap->Format() == Image_PixMap::ImgGrayF) {
1210 aPixMap->SetFormat (Image_PixMap::ImgAlphaF);
1212 anAspect = new Graphic3d_AspectMarker3d(aPixMap);
1213 aPntAspect->SetAspect(anAspect);
1215 aDrawer->SetPointAspect(aPntAspect);
1216 theAIS->SetHilightAttributes(aDrawer);
1220 } // namespace ModuleBase_Tools