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>
48 #include <QDoubleSpinBox>
49 #include <QGraphicsDropShadowEffect>
51 #include <QApplication>
52 #include <QMessageBox>
59 const double tolerance = 1e-7;
60 const double DEFAULT_DEVIATION_COEFFICIENT = 1.e-4;
62 //#define DEBUG_ACTIVATE_WINDOW
63 //#define DEBUG_SET_FOCUS
64 //#define DEBUG_SELECTION_INFO
66 #ifdef DEBUG_SELECTION_INFO
67 #include <ModuleBase_ISelection.h>
68 #include <ModuleBase_ViewerPrs.h>
70 #include <AIS_InteractiveContext.hxx>
71 #include <AIS_ListOfInteractive.hxx>
72 #include <AIS_ListIteratorOfListOfInteractive.hxx>
73 #include <AIS_Shape.hxx>
74 #include <TopoDS_Shape.hxx>
75 #include <AIS_LocalContext.hxx>
76 #include <NCollection_List.hxx>
77 #include <StdSelect_BRepOwner.hxx>
78 #include <TColStd_ListOfInteger.hxx>
79 #include <TColStd_ListIteratorOfListOfInteger.hxx>
82 namespace ModuleBase_Tools {
84 //******************************************************************
86 //******************************************************************
88 void adjustMargins(QWidget* theWidget)
92 adjustMargins(theWidget->layout());
95 void adjustMargins(QLayout* theLayout)
99 theLayout->setContentsMargins(2, 5, 2, 5);
100 theLayout->setSpacing(4);
103 void zeroMargins(QWidget* theWidget)
107 zeroMargins(theWidget->layout());
110 void zeroMargins(QLayout* theLayout)
114 theLayout->setContentsMargins(0, 0, 0, 0);
115 theLayout->setSpacing(5);
118 void activateWindow(QWidget* theWidget, const QString& theInfo)
120 theWidget->activateWindow();
122 #ifdef DEBUG_ACTIVATE_WINDOW
123 qDebug(QString("activateWindow: %1").arg(theInfo).toStdString().c_str());
127 void setFocus(QWidget* theWidget, const QString& theInfo)
129 theWidget->setFocus();
131 #ifdef DEBUG_SET_FOCUS
132 qDebug(QString("setFocus: %1").arg(theInfo).toStdString().c_str());
136 void setShadowEffect(QWidget* theWidget, const bool isSetEffect)
139 QGraphicsDropShadowEffect* aGlowEffect = new QGraphicsDropShadowEffect();
140 aGlowEffect->setOffset(.0);
141 aGlowEffect->setBlurRadius(10.0);
142 aGlowEffect->setColor(QColor(0, 170, 255)); // Light-blue color, #00AAFF
143 theWidget->setGraphicsEffect(aGlowEffect);
146 QGraphicsEffect* anEffect = theWidget->graphicsEffect();
148 anEffect->deleteLater();
149 theWidget->setGraphicsEffect(NULL);
153 QPixmap composite(const QString& theAdditionalIcon, const QString& theIcon)
155 QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
156 QImage anAditional(theAdditionalIcon);
161 int anAddWidth = anAditional.width();
162 int anAddHeight = anAditional.height();
164 int aWidth = anIcon.width();
165 int aHeight = anIcon.height();
167 int aStartWidthPos = aWidth - anAddWidth - 1;
168 int aStartHeightPos = aHeight - anAddHeight - 1;
170 for (int i = 0; i < anAddWidth && i + aStartWidthPos < aWidth; i++)
172 for (int j = 0; j < anAddHeight && j + aStartHeightPos < aHeight; j++)
174 if (qAlpha(anAditional.pixel(i, j)) > 0)
175 anIcon.setPixel(i + aStartWidthPos, j + aStartHeightPos, anAditional.pixel(i, j));
178 return QPixmap::fromImage(anIcon);
181 QPixmap lighter(const QString& theIcon, const int theLighterValue)
183 QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
187 QImage aResult = ModuleBase_IconFactory::loadImage(theIcon);
188 for (int i = 0; i < anIcon.width(); i++)
190 for (int j = 0; j < anIcon.height(); j++)
192 QRgb anRgb = anIcon.pixel(i, j);
193 QColor aPixelColor(qRed(anRgb), qGreen(anRgb), qBlue(anRgb),
194 qAlpha(aResult.pixel(i, j)));
196 QColor aLighterColor = aPixelColor.lighter(theLighterValue);
197 aResult.setPixel(i, j, qRgba(aLighterColor.red(), aLighterColor.green(),
198 aLighterColor.blue(), aLighterColor.alpha()));
201 return QPixmap::fromImage(aResult);
204 void setSpinText(ModuleBase_ParamSpinBox* theSpin, const QString& theText)
206 if (theSpin->text() == theText)
208 // In order to avoid extra text setting because it will
209 // reset cursor position in control
210 bool isBlocked = theSpin->blockSignals(true);
211 theSpin->setText(theText);
212 theSpin->blockSignals(isBlocked);
215 void setSpinValue(QDoubleSpinBox* theSpin, double theValue)
217 if (fabs(theSpin->value() - theValue) < tolerance)
219 bool isBlocked = theSpin->blockSignals(true);
220 theSpin->setValue(theValue);
221 theSpin->blockSignals(isBlocked);
224 void setSpinValue(ModuleBase_ParamSpinBox* theSpin, double theValue)
226 if (fabs(theSpin->value() - theValue) < tolerance)
228 bool isBlocked = theSpin->blockSignals(true);
229 theSpin->setValue(theValue);
230 theSpin->blockSignals(isBlocked);
233 void setSpinText(ModuleBase_ParamIntSpinBox* theSpin, const QString& theText)
235 // In order to avoid extra text setting because it will
236 // reset cursor position in control
237 if (theSpin->text() == theText)
239 bool isBlocked = theSpin->blockSignals(true);
240 theSpin->setText(theText);
241 theSpin->blockSignals(isBlocked);
244 void setSpinValue(ModuleBase_ParamIntSpinBox* theSpin, int theValue)
246 if (theSpin->value() == theValue)
248 bool isBlocked = theSpin->blockSignals(true);
249 theSpin->setValue(theValue);
250 theSpin->blockSignals(isBlocked);
253 QAction* createAction(const QIcon& theIcon, const QString& theText,
254 QObject* theParent, const QObject* theReceiver,
255 const char* theMember, const QString& theToolTip,
256 const QString& theStatusTip)
258 QAction* anAction = new QAction(theIcon, theText, theParent);
259 anAction->setToolTip(theToolTip.isEmpty() ? theText : theToolTip);
260 anAction->setStatusTip(!theStatusTip.isEmpty() ? theStatusTip :
261 (!theToolTip.isEmpty() ? theToolTip : theText));
263 QObject::connect(anAction, SIGNAL(triggered(bool)), theReceiver, theMember);
268 QString objectInfo(const ObjectPtr& theObj, const bool isUseAttributesInfo)
270 QString aFeatureStr = "feature";
274 std::ostringstream aPtrStr;
275 aPtrStr << "[" << theObj.get() << "]";
277 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theObj);
278 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
280 aFeatureStr.append(QString("(result%1)").arg(aPtrStr.str().c_str()).toStdString() .c_str());
281 if (aRes->isDisabled())
282 aFeatureStr.append("[disabled]");
283 if (aRes->isConcealed())
284 aFeatureStr.append("[concealed]");
285 if (ModelAPI_Tools::hasSubResults(aRes))
286 aFeatureStr.append("[hasSubResults]");
288 aFeature = ModelAPI_Feature::feature(aRes);
291 aFeatureStr.append(aPtrStr.str().c_str());
293 if (aFeature.get()) {
294 aFeatureStr.append(QString(": %1").arg(aFeature->getKind().c_str()).toStdString().c_str());
295 if (aFeature->data()->isValid()) {
296 aFeatureStr.append(QString(", name=%1").arg(theObj->data()->name().c_str()).toStdString()
299 if (isUseAttributesInfo) {
300 std::list<AttributePtr> anAttrs = aFeature->data()->attributes("");
301 std::list<AttributePtr>::const_iterator anIt = anAttrs.begin(), aLast = anAttrs.end();
303 for(; anIt != aLast; anIt++) {
304 AttributePtr anAttr = *anIt;
305 QString aValue = "not defined";
306 std::string aType = anAttr->attributeType();
307 if (aType == GeomDataAPI_Point2D::typeId()) {
308 std::shared_ptr<GeomDataAPI_Point2D> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
311 aValue = QString("(%1, %2)").arg(aPoint->x()).arg(aPoint->y());
313 else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
316 aValues.push_back(QString("%1: %2").arg(anAttr->id().c_str()).arg(aValue).toStdString().c_str());
318 if (!aValues.empty())
319 aFeatureStr.append(QString(", attributes: %1").arg(aValues.join(", ").toStdString().c_str()));
326 #ifdef DEBUG_SELECTION_INFO
327 QString getShapeTypeInfo(const int theType)
329 QString anInfo = "Undefined";
331 case TopAbs_COMPOUND: anInfo = "compound"; break;
332 case TopAbs_COMPSOLID: anInfo = "compsolid"; break;
333 case TopAbs_SOLID: anInfo = "solid"; break;
334 case TopAbs_SHELL: anInfo = "shell"; break;
335 case TopAbs_FACE: anInfo = "face"; break;
336 case TopAbs_WIRE: anInfo = "wire"; break;
337 case TopAbs_EDGE: anInfo = "edge"; break;
338 case TopAbs_VERTEX: anInfo = "vertex"; break;
339 case TopAbs_SHAPE: anInfo = "shape"; break;
345 QString getModeInfo(const int theMode)
347 QString anInfo = "Undefined";
349 case 0: anInfo = "SHAPE(0)"; break;
350 case 1: anInfo = "VERTEX(1)"; break;
351 case 2: anInfo = "EDGE(2)"; break;
352 case 3: anInfo = "WIRE(3)"; break;
353 case 4: anInfo = "FACE(4)"; break;
354 case 5: anInfo = "SHELL(5)"; break;
355 case 6: anInfo = "SOLID(6)"; break;
356 case 7: anInfo = "COMPSOLID(7)"; break;
357 case 8: anInfo = "COMPOUND(8)"; break;
358 case 100: anInfo = "Sel_Mode_First(100)"; break; //SketcherPrs_Tools
359 case 101: anInfo = "Sel_Constraint(101)"; break;
360 case 102: anInfo = "Sel_Dimension_All(102)"; break;
361 case 103: anInfo = "Sel_Dimension_Line(103)"; break;
362 case 104: anInfo = "Sel_Dimension_Text(104)"; break;
368 QString displayedInteractiveObjects(Handle(AIS_InteractiveContext)& theContext,
369 const bool theShapeInfoOnly = true)
371 if (theContext.IsNull())
373 AIS_ListOfInteractive aListOfIO;
374 theContext->DisplayedObjects(aListOfIO, false);
375 QStringList anObjects;
376 AIS_ListIteratorOfListOfInteractive aIt;
377 for (aIt.Initialize(aListOfIO); aIt.More(); aIt.Next()) {
378 Handle(AIS_InteractiveObject) anAISIO = aIt.Value();
379 Handle(AIS_Shape) aShapePrs = Handle(AIS_Shape)::DownCast(anAISIO);
380 if (theShapeInfoOnly && aShapePrs.IsNull())
383 QString anInfo = "IO";
384 std::ostringstream aPtrStr;
385 aPtrStr << "[" << anAISIO.Access() << "]";
386 anInfo += aPtrStr.str().c_str();
388 if (!aShapePrs.IsNull()) {
389 const TopoDS_Shape& aShape = aShapePrs->Shape();
391 Events_Error::throwException("An empty AIS presentation");
393 anInfo += QString(", shape type: %1").arg(getShapeTypeInfo(aShape.ShapeType()));
395 TColStd_ListOfInteger aTColModes;
396 theContext->ActivatedModes(anAISIO, aTColModes);
397 TColStd_ListIteratorOfListOfInteger itr( aTColModes );
398 QIntList aModesActivatedForIO;
399 bool isDeactivated = false;
401 for (; itr.More(); itr.Next() ) {
402 Standard_Integer aMode = itr.Value();
403 aModes.append(getModeInfo(aMode));
404 //int aShapeMode = (aMode > 8)? aMode : AIS_Shape::SelectionType(aMode);
406 if (aModes.size() > 0)
407 anInfo += QString(", activated modes: %1").arg(aModes.join(", "));
411 QString aValue = QString("displayedIO[%1]").arg(anObjects.size());
412 if (anObjects.size() > 0)
413 aValue += QString(":\n %1").arg(anObjects.join("\n "));
417 QString activeOwners(Handle(AIS_InteractiveContext)& theContext, const bool theShapeInfoOnly = true)
419 if (theContext.IsNull())
421 Handle(AIS_LocalContext) aLContext = theContext->LocalContext();
422 TCollection_AsciiString aSelectionName = aLContext->SelectionName();
423 aLContext->UnhilightPicked(Standard_False);
425 NCollection_List<Handle(SelectBasics_EntityOwner)> anActiveOwners;
426 aLContext->MainSelector()->ActiveOwners(anActiveOwners);
427 NCollection_List<Handle(SelectBasics_EntityOwner)>::Iterator anOwnersIt (anActiveOwners);
428 Handle(SelectMgr_EntityOwner) anOwner;
429 QStringList anObjects;
430 for (; anOwnersIt.More(); anOwnersIt.Next()) {
431 anOwner = Handle(SelectMgr_EntityOwner)::DownCast (anOwnersIt.Value());
432 Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
433 if (theShapeInfoOnly && BROwnr.IsNull())
436 QString anInfo = "Owner";
437 std::ostringstream aPtrStr;
438 aPtrStr << "[" << anOwner.Access() << "]";
439 anInfo += aPtrStr.str().c_str();
441 Handle(AIS_InteractiveObject) aAISObj =
442 Handle(AIS_InteractiveObject)::DownCast(anOwner->Selectable());
443 if (!aAISObj.IsNull()) {
444 std::ostringstream aPtrStr;
445 aPtrStr << "[" << aAISObj.Access() << "]";
446 anInfo += QString(", selectable(IO): %1").arg(aPtrStr.str().c_str());
449 if (!BROwnr.IsNull() && BROwnr->HasShape()) {
450 const TopoDS_Shape& aShape = BROwnr->Shape();
452 Events_Error::throwException("An empty AIS presentation");
454 anInfo += QString(", shape type: %1").arg(getShapeTypeInfo(aShape.ShapeType()));
458 QString aValue = QString("activeOwners[%1]").arg(anObjects.size());
459 if (anObjects.size() > 0)
460 aValue += QString(":\n %1").arg(anObjects.join("\n "));
464 QString selectedOwners(Handle(AIS_InteractiveContext)& theContext, const bool theShapeInfoOnly = true)
466 QStringList anObjects;
467 if (theContext.IsNull())
470 QList<long> aSelectedIds; // Remember of selected address in order to avoid duplicates
471 for (theContext->InitSelected(); theContext->MoreSelected(); theContext->NextSelected()) {
472 Handle(SelectMgr_EntityOwner) anOwner = theContext->SelectedOwner();
473 Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
474 if (theShapeInfoOnly && BROwnr.IsNull())
477 if (aSelectedIds.contains((long)anOwner.Access()))
479 aSelectedIds.append((long)anOwner.Access());
481 QString anInfo = "Owner";
482 std::ostringstream aPtrStr;
483 aPtrStr << "[" << anOwner.Access() << "]";
484 anInfo += aPtrStr.str().c_str();
486 if (!BROwnr.IsNull() && BROwnr->HasShape()) {
487 const TopoDS_Shape& aShape = BROwnr->Shape();
488 anInfo += QString(", shape type = %1").arg(getShapeTypeInfo(aShape.ShapeType()));
492 QString aValue = QString("selectedOwners[%1]").arg(anObjects.size());
493 if (anObjects.size() > 0)
494 aValue += QString(":\n %1").arg(anObjects.join("\n "));
499 void selectionInfo(Handle(AIS_InteractiveContext)& theContext, const std::string& thePrefix)
501 #ifdef DEBUG_SELECTION_INFO
502 QString aValue = QString("\n\n\nDEBUG_SELECTION_INFO for '%1'\n%2\n%3\n%4")
503 .arg(thePrefix.c_str())
504 .arg(displayedInteractiveObjects(theContext))
505 .arg(activeOwners(theContext))
506 .arg(selectedOwners(theContext));
507 qDebug(aValue.toStdString().c_str());
511 typedef QMap<QString, TopAbs_ShapeEnum> ShapeTypes;
512 static ShapeTypes myShapeTypes;
514 TopAbs_ShapeEnum shapeType(const QString& theType)
516 if (myShapeTypes.count() == 0) {
517 myShapeTypes["compound"] = TopAbs_COMPOUND;
518 myShapeTypes["compounds"] = TopAbs_COMPOUND;
519 myShapeTypes["compsolid"] = TopAbs_COMPSOLID;
520 myShapeTypes["compsolids"] = TopAbs_COMPSOLID;
521 myShapeTypes["solid"] = TopAbs_SOLID;
522 myShapeTypes["solids"] = TopAbs_SOLID;
523 myShapeTypes["shell"] = TopAbs_SHELL;
524 myShapeTypes["shells"] = TopAbs_SHELL;
525 myShapeTypes["face"] = TopAbs_FACE;
526 myShapeTypes["faces"] = TopAbs_FACE;
527 myShapeTypes["wire"] = TopAbs_WIRE;
528 myShapeTypes["wires"] = TopAbs_WIRE;
529 myShapeTypes["edge"] = TopAbs_EDGE;
530 myShapeTypes["edges"] = TopAbs_EDGE;
531 myShapeTypes["vertex"] = TopAbs_VERTEX;
532 myShapeTypes["vertices"] = TopAbs_VERTEX;
533 myShapeTypes["objects"] = TopAbs_SHAPE;
535 QString aType = theType.toLower();
536 if(myShapeTypes.contains(aType))
537 return myShapeTypes[aType];
538 Events_InfoMessage("ModuleBase_Tools", "Shape type defined in XML is not implemented!").send();
542 void checkObjects(const QObjectPtrList& theObjects, bool& hasResult, bool& hasFeature,
543 bool& hasParameter, bool& hasCompositeOwner)
547 hasParameter = false;
548 hasCompositeOwner = false;
549 foreach(ObjectPtr aObj, theObjects) {
550 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
551 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
552 ResultParameterPtr aConstruction = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aResult);
554 hasResult |= (aResult.get() != NULL);
555 hasFeature |= (aFeature.get() != NULL);
556 hasParameter |= (aConstruction.get() != NULL);
558 hasCompositeOwner |= (ModelAPI_Tools::compositeOwner(aFeature) != NULL);
559 if (hasFeature && hasResult && hasParameter && hasCompositeOwner)
564 bool setDefaultDeviationCoefficient(std::shared_ptr<GeomAPI_Shape> theGeomShape)
566 if (!theGeomShape.get())
568 // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
569 // correction of deviation for them should not influence to the application performance
570 GeomAPI_ShapeExplorer anExp(theGeomShape, GeomAPI_Shape::FACE);
571 bool anEmpty = anExp.empty();
572 return !anExp.more();
575 void setDefaultDeviationCoefficient(const std::shared_ptr<ModelAPI_Result>& theResult,
576 const Handle(Prs3d_Drawer)& theDrawer)
578 if (!theResult.get())
580 bool aUseDeviation = false;
582 std::string aResultGroup = theResult->groupName();
583 if (aResultGroup == ModelAPI_ResultConstruction::group())
584 aUseDeviation = true;
585 else if (aResultGroup == ModelAPI_ResultBody::group()) {
586 GeomShapePtr aGeomShape = theResult->shape();
587 if (aGeomShape.get())
588 aUseDeviation = setDefaultDeviationCoefficient(aGeomShape);
591 theDrawer->SetDeviationCoefficient(DEFAULT_DEVIATION_COEFFICIENT);
594 void setDefaultDeviationCoefficient(const TopoDS_Shape& theShape,
595 const Handle(Prs3d_Drawer)& theDrawer)
597 if (theShape.IsNull())
600 std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape());
601 aGeomShape->setImpl(new TopoDS_Shape(theShape));
602 if (setDefaultDeviationCoefficient(aGeomShape))
603 theDrawer->SetDeviationCoefficient(DEFAULT_DEVIATION_COEFFICIENT);
606 Quantity_Color color(const std::string& theSection,
607 const std::string& theName,
608 const std::string& theDefault)
610 std::vector<int> aColor = Config_PropManager::color(theSection, theName, theDefault);
611 return Quantity_Color(aColor[0] / 255., aColor[1] / 255., aColor[2] / 255., Quantity_TOC_RGB);
614 ObjectPtr getObject(const AttributePtr& theAttribute)
617 std::string anAttrType = theAttribute->attributeType();
618 if (anAttrType == ModelAPI_AttributeRefAttr::typeId()) {
619 AttributeRefAttrPtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
620 if (anAttr != NULL && anAttr->isObject())
621 anObject = anAttr->object();
623 if (anAttrType == ModelAPI_AttributeSelection::typeId()) {
624 AttributeSelectionPtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
626 anObject = anAttr->context();
628 if (anAttrType == ModelAPI_AttributeReference::typeId()) {
629 AttributeReferencePtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
630 if (anAttr.get() != NULL)
631 anObject = anAttr->value();
636 TopAbs_ShapeEnum getCompoundSubType(const TopoDS_Shape& theShape)
638 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
640 // for compounds check sub-shapes: it may be compound of needed type:
641 // Booleans may produce compounds of Solids
642 if (aShapeType == TopAbs_COMPOUND) {
643 for(TopoDS_Iterator aSubs(theShape); aSubs.More(); aSubs.Next()) {
644 if (!aSubs.Value().IsNull()) {
645 TopAbs_ShapeEnum aSubType = aSubs.Value().ShapeType();
646 if (aSubType == TopAbs_COMPOUND) { // compound of compound(s)
647 aShapeType = TopAbs_COMPOUND;
650 if (aShapeType == TopAbs_COMPOUND) {
651 aShapeType = aSubType;
652 } else if (aShapeType != aSubType) { // compound of shapes of different types
653 aShapeType = TopAbs_COMPOUND;
662 void getParameters(QStringList& theParameters)
664 theParameters.clear();
666 SessionPtr aSession = ModelAPI_Session::get();
667 std::list<DocumentPtr> aDocList;
668 DocumentPtr anActiveDocument = aSession->activeDocument();
669 DocumentPtr aRootDocument = aSession->moduleDocument();
670 aDocList.push_back(anActiveDocument);
671 if (anActiveDocument != aRootDocument) {
672 aDocList.push_back(aRootDocument);
674 std::string aGroupId = ModelAPI_ResultParameter::group();
675 for(std::list<DocumentPtr>::const_iterator it = aDocList.begin(); it != aDocList.end(); ++it) {
676 DocumentPtr aDocument = *it;
677 int aSize = aDocument->size(aGroupId);
678 for (int i = 0; i < aSize; i++) {
679 ObjectPtr anObject = aDocument->object(aGroupId, i);
680 std::string aParameterName = anObject->data()->name();
681 theParameters.append(aParameterName.c_str());
686 std::string findGreedAttribute(ModuleBase_IWorkshop* theWorkshop, const FeaturePtr& theFeature)
688 std::string anAttributeId;
690 std::string aXmlCfg, aDescription;
691 theWorkshop->module()->getXMLRepresentation(theFeature->getKind(), aXmlCfg, aDescription);
693 ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
694 std::string anAttributeTitle;
695 aFactory.getGreedAttribute(anAttributeId);
697 return anAttributeId;
700 bool hasObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
701 const std::shared_ptr<GeomAPI_Shape>& theShape,
702 ModuleBase_IWorkshop* theWorkshop,
703 const bool theTemporarily)
705 bool aHasObject = false;
706 if (!theAttribute.get())
709 std::string aType = theAttribute->attributeType();
710 if (aType == ModelAPI_AttributeReference::typeId()) {
711 AttributeReferencePtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
712 ObjectPtr aObject = aRef->value();
713 aHasObject = aObject && aObject->isSame(theObject);
714 //if (!(aObject && aObject->isSame(theObject))) {
715 // aRef->setValue(theObject);
717 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
718 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
720 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
721 if (anAttribute.get()) {
722 //aRefAttr->setAttr(anAttribute);
725 ObjectPtr aObject = aRefAttr->object();
726 aHasObject = aObject && aObject->isSame(theObject);
727 //if (!(aObject && aObject->isSame(theObject))) {
728 // aRefAttr->setObject(theObject);
731 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
732 /*AttributeSelectionPtr aSelectAttr =
733 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
734 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
735 if (aSelectAttr.get() != NULL) {
736 aSelectAttr->setValue(aResult, theShape, theTemporarily);
739 if (aType == ModelAPI_AttributeSelectionList::typeId()) {
740 AttributeSelectionListPtr aSelectionListAttr =
741 std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
742 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
743 aHasObject = aSelectionListAttr->isInList(aResult, theShape, theTemporarily);
744 //if (!theCheckIfAttributeHasObject || !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
745 // aSelectionListAttr->append(aResult, theShape, theTemporarily);
747 else if (aType == ModelAPI_AttributeRefList::typeId()) {
748 AttributeRefListPtr aRefListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
749 aHasObject = aRefListAttr->isInList(theObject);
750 //if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
751 // aRefListAttr->append(theObject);
753 else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
754 AttributeRefAttrListPtr aRefAttrListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
755 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
757 if (anAttribute.get()) {
758 aHasObject = aRefAttrListAttr->isInList(anAttribute);
759 //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
760 // aRefAttrListAttr->append(anAttribute);
763 aHasObject = aRefAttrListAttr->isInList(theObject);
764 //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
765 // aRefAttrListAttr->append(theObject);
771 void setObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
772 const GeomShapePtr& theShape, ModuleBase_IWorkshop* theWorkshop,
773 const bool theTemporarily, const bool theCheckIfAttributeHasObject)
775 if (!theAttribute.get())
778 std::string aType = theAttribute->attributeType();
779 if (aType == ModelAPI_AttributeReference::typeId()) {
780 AttributeReferencePtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
781 ObjectPtr aObject = aRef->value();
782 if (!(aObject && aObject->isSame(theObject))) {
783 aRef->setValue(theObject);
785 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
786 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
788 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
789 if (anAttribute.get())
790 aRefAttr->setAttr(anAttribute);
792 ObjectPtr aObject = aRefAttr->object();
793 if (!(aObject && aObject->isSame(theObject))) {
794 aRefAttr->setObject(theObject);
797 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
798 AttributeSelectionPtr aSelectAttr =
799 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
800 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
801 if (aSelectAttr.get() != NULL) {
802 aSelectAttr->setValue(aResult, theShape, theTemporarily);
805 if (aType == ModelAPI_AttributeSelectionList::typeId()) {
806 AttributeSelectionListPtr aSelectionListAttr =
807 std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
808 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
809 if (!theCheckIfAttributeHasObject || !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
810 aSelectionListAttr->append(aResult, theShape, theTemporarily);
812 else if (aType == ModelAPI_AttributeRefList::typeId()) {
813 AttributeRefListPtr aRefListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
814 if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
815 aRefListAttr->append(theObject);
817 else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
818 AttributeRefAttrListPtr aRefAttrListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
819 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
821 if (anAttribute.get()) {
822 if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
823 aRefAttrListAttr->append(anAttribute);
826 if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
827 aRefAttrListAttr->append(theObject);
832 GeomShapePtr getShape(const AttributePtr& theAttribute, ModuleBase_IWorkshop* theWorkshop)
835 if (!theAttribute.get())
838 std::string aType = theAttribute->attributeType();
839 if (aType == ModelAPI_AttributeReference::typeId()) {
840 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
841 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
842 if (aRefAttr.get() && !aRefAttr->isObject()) {
843 AttributePtr anAttribute = aRefAttr->attr();
844 aShape = theWorkshop->module()->findShape(anAttribute);
846 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
847 AttributeSelectionPtr aSelectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>
849 aShape = aSelectAttr->value();
854 void flushUpdated(ObjectPtr theObject)
856 blockUpdateViewer(true);
858 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
860 blockUpdateViewer(false);
863 void blockUpdateViewer(const bool theValue)
865 // the viewer update should be blocked in order to avoid the temporary feature content
866 // when the solver processes the feature, the redisplay message can be flushed
867 // what caused the display in the viewer preliminary states of object
868 // e.g. fillet feature, angle value change
869 std::shared_ptr<Events_Message> aMsg;
871 aMsg = std::shared_ptr<Events_Message>(
872 new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)));
875 // the viewer update should be unblocked
876 aMsg = std::shared_ptr<Events_Message>(
877 new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)));
879 Events_Loop::loop()->send(aMsg);
882 QString wrapTextByWords(const QString& theValue, QWidget* theWidget,
883 int theMaxLineInPixels)
885 static QFontMetrics tfm(theWidget ? theWidget->font() : QApplication::font());
886 static qreal phi = 2.618;
888 QRect aBounds = tfm.boundingRect(theValue);
889 if(aBounds.width() <= theMaxLineInPixels)
892 qreal s = aBounds.width() * aBounds.height();
893 qreal aGoldWidth = sqrt(s*phi);
895 QStringList aWords = theValue.split(" ", QString::SkipEmptyParts);
897 int n = aWords.count();
899 for (int i = 0; i < n; i++) {
900 QString aLineExt = aLine + " " + aWords[i];
901 qreal anWidthNonExt = tfm.boundingRect(aLine).width();
902 qreal anWidthExt = tfm.boundingRect(aLineExt).width();
903 qreal aDeltaNonExt = fabs(anWidthNonExt-aGoldWidth);
904 qreal aDeltaExt = fabs(anWidthExt-aGoldWidth);
905 if(aDeltaNonExt < aDeltaExt) {
907 aLines.append(aLine);
915 aLines.append(aLine);
917 QString aResult = aLines.join("\n");
921 //**************************************************************
922 void refsToFeatureInFeatureDocument(const ObjectPtr& theObject, std::set<FeaturePtr>& theRefFeatures)
924 FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
925 if (aFeature.get()) {
926 DocumentPtr aFeatureDoc = aFeature->document();
927 // 1. find references in the current document
928 aFeatureDoc->refsToFeature(aFeature, theRefFeatures, false);
933 //**************************************************************
934 bool isSubOfComposite(const ObjectPtr& theObject)
937 std::set<FeaturePtr> aRefFeatures;
938 refsToFeatureInFeatureDocument(theObject, aRefFeatures);
939 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
940 aLast = aRefFeatures.end();
941 for (; anIt != aLast && !isSub; anIt++) {
942 isSub = isSubOfComposite(theObject, *anIt);
947 //**************************************************************
948 bool isSubOfComposite(const ObjectPtr& theObject, const FeaturePtr& theFeature)
951 CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
952 if (aComposite.get()) {
953 isSub = aComposite->isSub(theObject);
954 // the recursive is possible, the parameters are sketch circle and extrusion cut. They are
955 // separated by composite sketch feature
957 int aNbSubs = aComposite->numberOfSubs();
958 for (int aSub = 0; aSub < aNbSubs && !isSub; aSub++) {
959 isSub = isSubOfComposite(theObject, aComposite->subFeature(aSub));
966 //**************************************************************
967 ResultPtr firstResult(const ObjectPtr& theObject)
969 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
970 if (!aResult.get()) {
971 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
973 aResult = aFeature->firstResult();
978 //**************************************************************
979 bool isFeatureOfResult(const FeaturePtr& theFeature, const std::string& theGroupOfResult)
981 bool isResult = false;
983 if (!theFeature->data()->isValid())
986 ResultPtr aFirstResult = theFeature->firstResult();
987 if (!aFirstResult.get())
990 return aFirstResult->groupName() == theGroupOfResult;
993 //**************************************************************
994 bool hasModuleDocumentFeature(const std::set<FeaturePtr>& theFeatures)
996 bool aFoundModuleDocumentObject = false;
997 DocumentPtr aModuleDoc = ModelAPI_Session::get()->moduleDocument();
999 std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(), aLast = theFeatures.end();
1000 for (; anIt != aLast && !aFoundModuleDocumentObject; anIt++) {
1001 FeaturePtr aFeature = *anIt;
1002 ResultPtr aResult = ModuleBase_Tools::firstResult(aFeature);
1003 if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group())
1005 aFoundModuleDocumentObject = aFeature->document() == aModuleDoc;
1008 return aFoundModuleDocumentObject;
1011 //**************************************************************
1012 bool askToDelete(const std::set<FeaturePtr> theFeatures,
1013 const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
1015 std::set<FeaturePtr>& theReferencesToDelete)
1017 QString aNotActivatedDocWrn;
1018 std::string aNotActivatedNames;
1019 if (!ModelAPI_Tools::allDocumentsActivated(aNotActivatedNames)) {
1020 if (ModuleBase_Tools::hasModuleDocumentFeature(theFeatures))
1021 aNotActivatedDocWrn = QObject::tr("Selected objects can be used in Part documents which are not loaded:%1.\n")
1022 .arg(aNotActivatedNames.c_str());
1025 std::set<FeaturePtr> aFeaturesRefsTo;
1026 std::set<FeaturePtr> aFeaturesRefsToParameter;
1027 std::set<FeaturePtr> aParameterFeatures;
1028 QStringList aPartFeatureNames;
1029 std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
1030 aLast = theFeatures.end();
1031 // separate features to references to parameter features and references to others
1032 for (; anIt != aLast; anIt++) {
1033 FeaturePtr aFeature = *anIt;
1034 if (theReferences.find(aFeature) == theReferences.end())
1037 if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
1038 aPartFeatureNames.append(aFeature->name().c_str());
1040 std::set<FeaturePtr> aRefFeatures;
1041 std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
1042 std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
1043 for (; aRefIt != aRefLast; aRefIt++) {
1044 FeaturePtr aRefFeature = *aRefIt;
1045 if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
1046 aRefFeatures.find(aRefFeature) == aRefFeatures.end()) // it is not added
1047 aRefFeatures.insert(aRefFeature);
1050 if (isFeatureOfResult(aFeature, ModelAPI_ResultParameter::group())) {
1051 aFeaturesRefsToParameter.insert(aRefFeatures.begin(), aRefFeatures.end());
1052 aParameterFeatures.insert(aFeature);
1055 theReferencesToDelete.insert(aRefFeatures.begin(), aRefFeatures.end());
1059 std::set<FeaturePtr> aFeaturesRefsToParameterOnly;
1060 anIt = aFeaturesRefsToParameter.begin();
1061 aLast = aFeaturesRefsToParameter.end();
1062 // separate features to references to parameter features and references to others
1063 QStringList aParamFeatureNames;
1064 for (; anIt != aLast; anIt++) {
1065 FeaturePtr aFeature = *anIt;
1066 if (theReferencesToDelete.find(aFeature) == theReferencesToDelete.end()) {
1067 aFeaturesRefsToParameterOnly.insert(aFeature);
1068 aParamFeatureNames.append(aFeature->name().c_str());
1071 aParamFeatureNames.sort();
1072 QStringList anOtherFeatureNames;
1073 anIt = theReferencesToDelete.begin();
1074 aLast = theReferencesToDelete.end();
1075 for (; anIt != aLast; anIt++) {
1076 FeaturePtr aFeature = *anIt;
1077 if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
1078 aPartFeatureNames.append(aFeature->name().c_str());
1080 anOtherFeatureNames.append(aFeature->name().c_str());
1082 aPartFeatureNames.sort();
1083 anOtherFeatureNames.sort();
1085 bool aCanReplaceParameters = !aFeaturesRefsToParameterOnly.empty();
1087 QMessageBox aMessageBox(theParent);
1088 aMessageBox.setWindowTitle(QObject::tr("Delete features"));
1089 aMessageBox.setIcon(QMessageBox::Warning);
1090 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1091 aMessageBox.setDefaultButton(QMessageBox::No);
1094 QString aSep = ", ";
1095 if (!aPartFeatureNames.empty())
1096 aText += QString(QObject::tr("The following parts will be deleted: %1.\n")).arg(aPartFeatureNames.join(aSep));
1097 if (!aNotActivatedDocWrn.isEmpty())
1098 aText += aNotActivatedDocWrn;
1099 if (!anOtherFeatureNames.empty())
1100 aText += QString(QObject::tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n"))
1101 .arg(anOtherFeatureNames.join(aSep));
1102 if (!aParamFeatureNames.empty()) {
1103 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"))
1104 .arg(aParamFeatureNames.join(aSep));
1105 QPushButton *aReplaceButton = aMessageBox.addButton(QObject::tr("Replace"), QMessageBox::ActionRole);
1108 if (!aText.isEmpty()) {
1109 aText += "Would you like to continue?";
1110 aMessageBox.setText(aText);
1112 QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1114 if (aButtonRole == QMessageBox::NoRole)
1117 if (aButtonRole == QMessageBox::ActionRole) {
1118 foreach (FeaturePtr aObj, aParameterFeatures)
1119 ModelAPI_ReplaceParameterMessage::send(aObj, 0);
1122 theReferencesToDelete.insert(aFeaturesRefsToParameterOnly.begin(), aFeaturesRefsToParameterOnly.end());
1127 //**************************************************************
1128 void convertToFeatures(const QObjectPtrList& theObjects, std::set<FeaturePtr>& theFeatures)
1130 QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1131 for(; anIt != aLast; anIt++) {
1132 ObjectPtr anObject = *anIt;
1133 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1134 // for parameter result, use the corresponded reature to be removed
1135 if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1136 aFeature = ModelAPI_Feature::feature(anObject);
1138 theFeatures.insert(aFeature);
1142 void translate(const std::string& theContext, std::string& theMessage)
1144 if (!theMessage.empty()) {
1145 std::string aStr = Config_Translator::translate(theContext, theMessage);
1146 if (!aStr.empty()) {
1147 std::string aCodec = Config_Translator::codec(theContext);
1148 theMessage = QTextCodec::codecForName(aCodec.c_str())->toUnicode(aStr.c_str()).toStdString();
1153 } // namespace ModuleBase_Tools