1 // Copyright (C) 2014-2017 CEA/DEN, EDF R&D
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
21 #include "ModuleBase_Tools.h"
23 #include <ModuleBase_ParamIntSpinBox.h>
24 #include <ModuleBase_ParamSpinBox.h>
25 #include <ModuleBase_WidgetFactory.h>
26 #include <ModuleBase_IWorkshop.h>
27 #include <ModuleBase_IModule.h>
28 #include <ModuleBase_IViewer.h>
29 #include <ModuleBase_IconFactory.h>
30 #include <ModuleBase_ResultPrs.h>
31 #include <ModuleBase_ViewerPrs.h>
33 #include <ModelAPI_Attribute.h>
34 #include <ModelAPI_AttributeRefAttr.h>
35 #include <ModelAPI_AttributeReference.h>
36 #include <ModelAPI_AttributeSelection.h>
37 #include <ModelAPI_AttributeSelectionList.h>
38 #include <ModelAPI_AttributeRefList.h>
39 #include <ModelAPI_AttributeRefAttrList.h>
40 #include <ModelAPI_ResultPart.h>
41 #include <ModelAPI_ResultConstruction.h>
42 #include <ModelAPI_AttributeString.h>
43 #include <ModelAPI_Expression.h>
44 #include <Events_Loop.h>
46 #include <ModelAPI_Data.h>
47 #include <ModelAPI_Result.h>
48 #include <ModelAPI_ResultParameter.h>
49 #include <ModelAPI_Tools.h>
50 #include <ModelAPI_Session.h>
51 #include <ModelAPI_Events.h>
52 #include <ModelAPI_Folder.h>
54 #include <ModelGeomAlgo_Point2D.h>
56 #include <StdSelect_BRepOwner.hxx>
57 #include <TopoDS_Iterator.hxx>
58 #include <AIS_InteractiveContext.hxx>
59 #include <Prs3d_LineAspect.hxx>
60 #include <Prs3d_PlaneAspect.hxx>
62 #include <GeomDataAPI_Point2D.h>
63 #include <Events_InfoMessage.h>
64 #include <GeomAPI_ShapeExplorer.h>
66 #include <Config_PropManager.h>
67 #include <Config_Translator.h>
69 #include <Prs3d_PointAspect.hxx>
70 #include <Graphic3d_AspectMarker3d.hxx>
72 #include <Image_AlienPixMap.hxx>
78 #include <QDoubleSpinBox>
79 #include <QGraphicsDropShadowEffect>
81 #include <QApplication>
82 #include <QMessageBox>
90 #pragma warning(disable : 4996) // for getenv
93 const double tolerance = 1e-7;
94 const double DEFAULT_DEVIATION_COEFFICIENT = 1.e-4;
96 //#define DEBUG_ACTIVATE_WINDOW
97 //#define DEBUG_SET_FOCUS
105 namespace ModuleBase_Tools {
107 //******************************************************************
109 //******************************************************************
111 void adjustMargins(QWidget* theWidget)
115 adjustMargins(theWidget->layout());
118 void adjustMargins(QLayout* theLayout)
122 theLayout->setContentsMargins(2, 5, 2, 5);
123 theLayout->setSpacing(4);
126 void zeroMargins(QWidget* theWidget)
130 zeroMargins(theWidget->layout());
133 void zeroMargins(QLayout* theLayout)
137 theLayout->setContentsMargins(0, 0, 0, 0);
138 theLayout->setSpacing(5);
141 void activateWindow(QWidget* theWidget, const QString& theInfo)
144 theWidget->activateWindow();
148 #ifdef DEBUG_ACTIVATE_WINDOW
149 qDebug(QString("activateWindow: %1").arg(theInfo).toStdString().c_str());
153 void setFocus(QWidget* theWidget, const QString& theInfo)
155 activateWindow(theWidget);
156 theWidget->setFocus();
157 // rectangle of focus is not visible on tool button widgets
158 theWidget->repaint();
159 #ifdef DEBUG_SET_FOCUS
160 qDebug(QString("setFocus: %1").arg(theInfo).toStdString().c_str());
164 void setShadowEffect(QWidget* theWidget, const bool isSetEffect)
167 QGraphicsDropShadowEffect* aGlowEffect = new QGraphicsDropShadowEffect();
168 aGlowEffect->setOffset(.0);
169 aGlowEffect->setBlurRadius(10.0);
170 aGlowEffect->setColor(QColor(0, 170, 255)); // Light-blue color, #00AAFF
171 theWidget->setGraphicsEffect(aGlowEffect);
174 QGraphicsEffect* anEffect = theWidget->graphicsEffect();
176 anEffect->deleteLater();
177 theWidget->setGraphicsEffect(NULL);
181 QPixmap composite(const QString& theAdditionalIcon, const QString& theIcon)
183 QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
184 QImage anAditional(theAdditionalIcon);
185 return composite(anAditional, anIcon);
188 QPixmap composite(const QImage& theAdditionalIcon, QImage& theIcon)
190 if (theIcon.isNull())
193 int anAddWidth = theAdditionalIcon.width();
194 int anAddHeight = theAdditionalIcon.height();
196 int aWidth = theIcon.width();
197 int aHeight = theIcon.height();
199 int aStartWidthPos = aWidth - anAddWidth;
200 int aStartHeightPos = aHeight - anAddHeight;
202 for (int i = 0; i < anAddWidth && i + aStartWidthPos < aWidth; i++)
204 for (int j = 0; j < anAddHeight && j + aStartHeightPos < aHeight; j++)
206 if (qAlpha(theAdditionalIcon.pixel(i, j)) > 0)
207 theIcon.setPixel(i + aStartWidthPos, j + aStartHeightPos, theAdditionalIcon.pixel(i, j));
210 return QPixmap::fromImage(theIcon);
213 QPixmap lighter(const QString& theIcon, const int theLighterValue)
215 QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
219 QImage aResult = ModuleBase_IconFactory::loadImage(theIcon);
220 for (int i = 0; i < anIcon.width(); i++)
222 for (int j = 0; j < anIcon.height(); j++)
224 QRgb anRgb = anIcon.pixel(i, j);
225 QColor aPixelColor(qRed(anRgb), qGreen(anRgb), qBlue(anRgb),
226 qAlpha(aResult.pixel(i, j)));
228 QColor aLighterColor = aPixelColor.lighter(theLighterValue);
229 aResult.setPixel(i, j, qRgba(aLighterColor.red(), aLighterColor.green(),
230 aLighterColor.blue(), aLighterColor.alpha()));
233 return QPixmap::fromImage(aResult);
236 void setSpinText(ModuleBase_ParamSpinBox* theSpin, const QString& theText)
238 if (theSpin->text() == theText)
240 // In order to avoid extra text setting because it will
241 // reset cursor position in control
242 bool isBlocked = theSpin->blockSignals(true);
243 theSpin->setText(theText);
244 theSpin->blockSignals(isBlocked);
247 void setSpinValue(QDoubleSpinBox* theSpin, double theValue)
249 if (fabs(theSpin->value() - theValue) < tolerance)
251 bool isBlocked = theSpin->blockSignals(true);
252 theSpin->setValue(theValue);
253 theSpin->blockSignals(isBlocked);
256 void setSpinValue(ModuleBase_ParamSpinBox* theSpin, double theValue)
258 if (fabs(theSpin->value() - theValue) < tolerance)
260 bool isBlocked = theSpin->blockSignals(true);
261 theSpin->setValue(theValue);
262 theSpin->blockSignals(isBlocked);
265 void setSpinText(ModuleBase_ParamIntSpinBox* theSpin, const QString& theText)
267 // In order to avoid extra text setting because it will
268 // reset cursor position in control
269 if (theSpin->text() == theText)
271 bool isBlocked = theSpin->blockSignals(true);
272 theSpin->setText(theText);
273 theSpin->blockSignals(isBlocked);
276 void setSpinValue(ModuleBase_ParamIntSpinBox* theSpin, int theValue)
278 if (theSpin->value() == theValue)
280 bool isBlocked = theSpin->blockSignals(true);
281 theSpin->setValue(theValue);
282 theSpin->blockSignals(isBlocked);
285 QAction* createAction(const QIcon& theIcon, const QString& theText,
286 QObject* theParent, const QObject* theReceiver,
287 const char* theMember, const QString& theToolTip,
288 const QString& theStatusTip)
290 QAction* anAction = new QAction(theIcon, theText, theParent);
291 anAction->setToolTip(theToolTip.isEmpty() ? theText : theToolTip);
292 anAction->setStatusTip(!theStatusTip.isEmpty() ? theStatusTip :
293 (!theToolTip.isEmpty() ? theToolTip : theText));
295 QObject::connect(anAction, SIGNAL(triggered(bool)), theReceiver, theMember);
301 QString objectName(const ObjectPtr& theObj)
306 return theObj->data()->name().c_str();
309 QString objectInfo(const ObjectPtr& theObj, const bool isUseAttributesInfo)
311 QString aFeatureStr = "feature";
315 std::ostringstream aPtrStr;
316 aPtrStr << "[" << theObj.get() << "]";
318 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theObj);
319 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
321 aFeatureStr.append(QString("(result%1)").arg(aPtrStr.str().c_str()).toStdString() .c_str());
322 if (aRes->isDisabled())
323 aFeatureStr.append("[disabled]");
324 if (aRes->isConcealed())
325 aFeatureStr.append("[concealed]");
326 if (ModelAPI_Tools::hasSubResults(aRes))
327 aFeatureStr.append("[hasSubResults]");
329 aFeature = ModelAPI_Feature::feature(aRes);
332 aFeatureStr.append(aPtrStr.str().c_str());
334 if (aFeature.get()) {
335 aFeatureStr.append(QString(": %1").arg(aFeature->getKind().c_str()).toStdString().c_str());
336 if (aFeature->data()->isValid()) {
337 aFeatureStr.append(QString(", name=%1").arg(theObj->data()->name().c_str()).toStdString()
340 if (isUseAttributesInfo) {
341 std::set<std::shared_ptr<ModelAPI_Attribute> > anAttributes;
342 std::string aPointsInfo = ModelGeomAlgo_Point2D::getPontAttributesInfo(aFeature,
343 anAttributes).c_str();
344 if (!aPointsInfo.empty())
345 aFeatureStr.append(QString(", attributes: %1")
346 .arg(aPointsInfo.c_str()).toStdString().c_str());
354 typedef QMap<QString, int> ShapeTypes;
355 static ShapeTypes myShapeTypes;
357 int shapeType(const QString& theType)
359 if (myShapeTypes.count() == 0) {
360 myShapeTypes["compound"] = TopAbs_COMPOUND;
361 myShapeTypes["compounds"] = TopAbs_COMPOUND;
362 myShapeTypes["compsolid"] = TopAbs_COMPSOLID;
363 myShapeTypes["compsolids"] = TopAbs_COMPSOLID;
364 myShapeTypes["solid"] = TopAbs_SOLID;
365 myShapeTypes["solids"] = TopAbs_SOLID;
366 myShapeTypes["shell"] = TopAbs_SHELL;
367 myShapeTypes["shells"] = TopAbs_SHELL;
368 myShapeTypes["face"] = TopAbs_FACE;
369 myShapeTypes["faces"] = TopAbs_FACE;
370 myShapeTypes["wire"] = TopAbs_WIRE;
371 myShapeTypes["wires"] = TopAbs_WIRE;
372 myShapeTypes["edge"] = TopAbs_EDGE;
373 myShapeTypes["edges"] = TopAbs_EDGE;
374 myShapeTypes["vertex"] = TopAbs_VERTEX;
375 myShapeTypes["vertices"] = TopAbs_VERTEX;
376 myShapeTypes["object"] = ModuleBase_ResultPrs::Sel_Result;
377 myShapeTypes["objects"] = ModuleBase_ResultPrs::Sel_Result;
379 QString aType = theType.toLower();
380 if(myShapeTypes.contains(aType))
381 return myShapeTypes[aType];
382 Events_InfoMessage("ModuleBase_Tools", "Shape type defined in XML is not implemented!").send();
386 void checkObjects(const QObjectPtrList& theObjects, bool& hasResult, bool& hasFeature,
387 bool& hasParameter, bool& hasCompositeOwner, bool& hasResultInHistory,
392 hasParameter = false;
393 hasCompositeOwner = false;
394 hasResultInHistory = false;
396 foreach(ObjectPtr aObj, theObjects) {
397 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
398 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
399 FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(aObj);
400 ResultParameterPtr aConstruction = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aResult);
402 hasResult |= (aResult.get() != NULL);
403 hasFeature |= (aFeature.get() != NULL);
404 hasFolder |= (aFolder.get() != NULL);
405 hasParameter |= (aConstruction.get() != NULL);
407 hasCompositeOwner |= (ModelAPI_Tools::compositeOwner(aFeature) != NULL);
409 if (!hasResultInHistory && aResult.get()) {
410 FeaturePtr aFeature = ModelAPI_Feature::feature(aResult);
411 hasResultInHistory = aFeature.get() && aFeature->isInHistory();
414 if (hasFeature && hasResult && hasParameter && hasCompositeOwner && hasFeature)
419 /*bool setDefaultDeviationCoefficient(std::shared_ptr<GeomAPI_Shape> theGeomShape)
421 if (!theGeomShape.get())
423 // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
424 // correction of deviation for them should not influence to the application performance
425 GeomAPI_ShapeExplorer anExp(theGeomShape, GeomAPI_Shape::FACE);
426 bool anEmpty = anExp.empty();
427 return !anExp.more();
430 /*void setDefaultDeviationCoefficient(const std::shared_ptr<ModelAPI_Result>& theResult,
431 const Handle(Prs3d_Drawer)& theDrawer)
433 if (!theResult.get())
435 bool aUseDeviation = false;
437 std::string aResultGroup = theResult->groupName();
438 if (aResultGroup == ModelAPI_ResultConstruction::group())
439 aUseDeviation = true;
440 else if (aResultGroup == ModelAPI_ResultBody::group()) {
441 GeomShapePtr aGeomShape = theResult->shape();
442 if (aGeomShape.get())
443 aUseDeviation = setDefaultDeviationCoefficient(aGeomShape);
446 theDrawer->SetDeviationCoefficient(DEFAULT_DEVIATION_COEFFICIENT);
449 void setDefaultDeviationCoefficient(const TopoDS_Shape& theShape,
450 const Handle(Prs3d_Drawer)& theDrawer)
452 if (theShape.IsNull())
455 std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape());
456 aGeomShape->setImpl(new TopoDS_Shape(theShape));
458 // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
459 // correction of deviation for them should not influence to the application performance
460 GeomAPI_ShapeExplorer anExp(aGeomShape, GeomAPI_Shape::FACE);
461 bool isConstruction = !anExp.more();
465 aDeflection = Config_PropManager::real("Visualization", "construction_deflection");
467 aDeflection = Config_PropManager::real("Visualization", "body_deflection");
469 theDrawer->SetDeviationCoefficient(aDeflection);
472 Quantity_Color color(const std::string& theSection,
473 const std::string& theName)
475 std::vector<int> aColor = Config_PropManager::color(theSection, theName);
476 return Quantity_Color(aColor[0] / 255., aColor[1] / 255., aColor[2] / 255., Quantity_TOC_RGB);
479 ObjectPtr getObject(const AttributePtr& theAttribute)
482 std::string anAttrType = theAttribute->attributeType();
483 if (anAttrType == ModelAPI_AttributeRefAttr::typeId()) {
484 AttributeRefAttrPtr anAttr =
485 std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
486 if (anAttr != NULL && anAttr->isObject())
487 anObject = anAttr->object();
489 if (anAttrType == ModelAPI_AttributeSelection::typeId()) {
490 AttributeSelectionPtr anAttr =
491 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
493 anObject = anAttr->context();
495 if (anAttrType == ModelAPI_AttributeReference::typeId()) {
496 AttributeReferencePtr anAttr =
497 std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
498 if (anAttr.get() != NULL)
499 anObject = anAttr->value();
504 TopAbs_ShapeEnum getCompoundSubType(const TopoDS_Shape& theShape)
506 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
508 // for compounds check sub-shapes: it may be compound of needed type:
509 // Booleans may produce compounds of Solids
510 if (aShapeType == TopAbs_COMPOUND) {
511 for(TopoDS_Iterator aSubs(theShape); aSubs.More(); aSubs.Next()) {
512 if (!aSubs.Value().IsNull()) {
513 TopAbs_ShapeEnum aSubType = aSubs.Value().ShapeType();
514 if (aSubType == TopAbs_COMPOUND) { // compound of compound(s)
515 aShapeType = TopAbs_COMPOUND;
518 if (aShapeType == TopAbs_COMPOUND) {
519 aShapeType = aSubType;
520 } else if (aShapeType != aSubType) { // compound of shapes of different types
521 aShapeType = TopAbs_COMPOUND;
530 TopoDS_Shape getSelectedShape(const std::shared_ptr<ModuleBase_ViewerPrs>& thePrs)
532 if (thePrs->shape().get())
533 return thePrs->shape()->impl<TopoDS_Shape>();
535 Handle(StdSelect_BRepOwner) anOwner = Handle(StdSelect_BRepOwner)::DownCast(thePrs->owner());
536 if (!anOwner.IsNull())
537 return anOwner->Shape();
539 return TopoDS_Shape();
542 void getParameters(QStringList& theParameters)
544 theParameters.clear();
546 SessionPtr aSession = ModelAPI_Session::get();
547 std::list<DocumentPtr> aDocList;
548 DocumentPtr anActiveDocument = aSession->activeDocument();
549 DocumentPtr aRootDocument = aSession->moduleDocument();
550 aDocList.push_back(anActiveDocument);
551 if (anActiveDocument != aRootDocument) {
552 aDocList.push_back(aRootDocument);
554 std::string aGroupId = ModelAPI_ResultParameter::group();
555 for(std::list<DocumentPtr>::const_iterator it = aDocList.begin(); it != aDocList.end(); ++it) {
556 DocumentPtr aDocument = *it;
557 int aSize = aDocument->size(aGroupId);
558 for (int i = 0; i < aSize; i++) {
559 ObjectPtr anObject = aDocument->object(aGroupId, i);
560 std::string aParameterName = anObject->data()->name();
561 theParameters.append(aParameterName.c_str());
566 std::string findGreedAttribute(ModuleBase_IWorkshop* theWorkshop,
567 const FeaturePtr& theFeature)
569 std::string anAttributeId;
571 std::string aXmlCfg, aDescription;
572 theWorkshop->module()->getXMLRepresentation(theFeature->getKind(), aXmlCfg, aDescription);
574 ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
575 std::string anAttributeTitle;
576 aFactory.getGreedAttribute(anAttributeId);
578 return anAttributeId;
581 bool hasObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
582 const std::shared_ptr<GeomAPI_Shape>& theShape,
583 ModuleBase_IWorkshop* theWorkshop,
584 const bool theTemporarily)
586 bool aHasObject = false;
587 if (!theAttribute.get())
590 std::string aType = theAttribute->attributeType();
591 if (aType == ModelAPI_AttributeReference::typeId()) {
592 AttributeReferencePtr aRef =
593 std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
594 ObjectPtr aObject = aRef->value();
595 aHasObject = aObject && aObject->isSame(theObject);
596 //if (!(aObject && aObject->isSame(theObject))) {
597 // aRef->setValue(theObject);
599 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
600 AttributeRefAttrPtr aRefAttr =
601 std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
603 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
604 if (anAttribute.get()) {
605 //aRefAttr->setAttr(anAttribute);
608 ObjectPtr aObject = aRefAttr->object();
609 aHasObject = aObject && aObject->isSame(theObject);
610 //if (!(aObject && aObject->isSame(theObject))) {
611 // aRefAttr->setObject(theObject);
614 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
615 /*AttributeSelectionPtr aSelectAttr =
616 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
617 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
618 if (aSelectAttr.get() != NULL) {
619 aSelectAttr->setValue(aResult, theShape, theTemporarily);
622 if (aType == ModelAPI_AttributeSelectionList::typeId()) {
623 AttributeSelectionListPtr aSelectionListAttr =
624 std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
625 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
626 aHasObject = aSelectionListAttr->isInList(aResult, theShape, theTemporarily);
628 else if (aType == ModelAPI_AttributeRefList::typeId()) {
629 AttributeRefListPtr aRefListAttr =
630 std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
631 aHasObject = aRefListAttr->isInList(theObject);
632 //if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
633 // aRefListAttr->append(theObject);
635 else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
636 AttributeRefAttrListPtr aRefAttrListAttr =
637 std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
638 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
640 if (anAttribute.get()) {
641 aHasObject = aRefAttrListAttr->isInList(anAttribute);
642 //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
643 // aRefAttrListAttr->append(anAttribute);
646 aHasObject = aRefAttrListAttr->isInList(theObject);
647 //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
648 // aRefAttrListAttr->append(theObject);
654 bool setObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
655 const GeomShapePtr& theShape, ModuleBase_IWorkshop* theWorkshop,
656 const bool theTemporarily, const bool theCheckIfAttributeHasObject)
658 if (!theAttribute.get())
662 std::string aType = theAttribute->attributeType();
663 if (aType == ModelAPI_AttributeReference::typeId()) {
664 AttributeReferencePtr aRef =
665 std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
666 ObjectPtr aObject = aRef->value();
667 if (!(aObject && aObject->isSame(theObject))) {
668 aRef->setValue(theObject);
670 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
671 AttributeRefAttrPtr aRefAttr =
672 std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
674 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
675 if (anAttribute.get())
676 aRefAttr->setAttr(anAttribute);
678 ObjectPtr aObject = aRefAttr->object();
679 if (!(aObject && aObject->isSame(theObject))) {
680 aRefAttr->setObject(theObject);
683 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
684 AttributeSelectionPtr aSelectAttr =
685 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
686 if (aSelectAttr.get() != NULL) {
687 aSelectAttr->setValue(theObject, theShape, theTemporarily);
690 if (aType == ModelAPI_AttributeSelectionList::typeId()) {
691 AttributeSelectionListPtr aSelectionListAttr =
692 std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
693 if (!theCheckIfAttributeHasObject ||
694 !aSelectionListAttr->isInList(theObject, theShape, theTemporarily))
695 aSelectionListAttr->append(theObject, theShape, theTemporarily);
697 else if (aType == ModelAPI_AttributeRefList::typeId()) {
698 AttributeRefListPtr aRefListAttr =
699 std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
700 if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject)) {
702 aRefListAttr->append(theObject);
707 else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
708 AttributeRefAttrListPtr aRefAttrListAttr =
709 std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
710 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
712 if (anAttribute.get()) {
713 if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
714 aRefAttrListAttr->append(anAttribute);
717 if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject)) {
719 aRefAttrListAttr->append(theObject);
728 GeomShapePtr getShape(const AttributePtr& theAttribute, ModuleBase_IWorkshop* theWorkshop)
731 if (!theAttribute.get())
734 std::string aType = theAttribute->attributeType();
735 if (aType == ModelAPI_AttributeReference::typeId()) {
736 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
737 AttributeRefAttrPtr aRefAttr =
738 std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
739 if (aRefAttr.get() && !aRefAttr->isObject()) {
740 AttributePtr anAttribute = aRefAttr->attr();
741 aShape = theWorkshop->module()->findShape(anAttribute);
743 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
744 AttributeSelectionPtr aSelectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>
746 aShape = aSelectAttr->value();
748 else // Geom2D point processing
749 aShape = theWorkshop->module()->findShape(theAttribute);
753 void flushUpdated(ObjectPtr theObject)
755 blockUpdateViewer(true);
757 // Fix the problem of not previewed results of constraints applied. Flush Create/Delete
758 // (for the sketch result) to start processing of the sketch in the solver.
759 // TODO: these flushes should be moved in a separate method provided by Model
760 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
761 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
762 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
764 blockUpdateViewer(false);
767 void blockUpdateViewer(const bool theValue)
769 // the viewer update should be blocked in order to avoid the temporary feature content
770 // when the solver processes the feature, the redisplay message can be flushed
771 // what caused the display in the viewer preliminary states of object
772 // e.g. fillet feature, angle value change
773 std::shared_ptr<Events_Message> aMsg;
775 aMsg = std::shared_ptr<Events_Message>(
776 new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)));
779 // the viewer update should be unblocked
780 aMsg = std::shared_ptr<Events_Message>(
781 new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)));
783 Events_Loop::loop()->send(aMsg);
786 QString wrapTextByWords(const QString& theValue, QWidget* theWidget,
787 int theMaxLineInPixels)
789 static QFontMetrics tfm(theWidget ? theWidget->font() : QApplication::font());
790 static qreal phi = 2.618;
792 QRect aBounds = tfm.boundingRect(theValue);
793 if(aBounds.width() <= theMaxLineInPixels)
796 qreal s = aBounds.width() * aBounds.height();
797 qreal aGoldWidth = sqrt(s*phi);
799 QStringList aWords = theValue.split(" ", QString::SkipEmptyParts);
801 int n = aWords.count();
803 for (int i = 0; i < n; i++) {
804 QString aLineExt = aLine + " " + aWords[i];
805 qreal anWidthNonExt = tfm.boundingRect(aLine).width();
806 qreal anWidthExt = tfm.boundingRect(aLineExt).width();
807 qreal aDeltaNonExt = fabs(anWidthNonExt-aGoldWidth);
808 qreal aDeltaExt = fabs(anWidthExt-aGoldWidth);
809 if(aDeltaNonExt < aDeltaExt) {
811 aLines.append(aLine);
819 aLines.append(aLine);
821 QString aResult = aLines.join("\n");
825 //**************************************************************
826 QLocale doubleLocale()
828 // VSR 01/07/2010: Disable thousands separator for spin box
829 // (to avoid inconsistency of double-2-string and string-2-double conversion)
831 aLocale.setNumberOptions(aLocale.numberOptions() |
832 QLocale::OmitGroupSeparator |
833 QLocale::RejectGroupSeparator);
837 //**************************************************************
838 void refsToFeatureInFeatureDocument(const ObjectPtr& theObject,
839 std::set<FeaturePtr>& theRefFeatures)
841 FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
842 if (aFeature.get()) {
843 DocumentPtr aFeatureDoc = aFeature->document();
844 // 1. find references in the current document
845 aFeatureDoc->refsToFeature(aFeature, theRefFeatures, false);
850 //**************************************************************
851 /*bool isSubOfComposite(const ObjectPtr& theObject)
854 std::set<FeaturePtr> aRefFeatures;
855 refsToFeatureInFeatureDocument(theObject, aRefFeatures);
856 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
857 aLast = aRefFeatures.end();
858 for (; anIt != aLast && !isSub; anIt++) {
859 isSub = isSubOfComposite(theObject, *anIt);
864 //**************************************************************
865 /*bool isSubOfComposite(const ObjectPtr& theObject, const FeaturePtr& theFeature)
868 CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
869 if (aComposite.get()) {
870 isSub = aComposite->isSub(theObject);
871 // the recursive is possible, the parameters are sketch circle and extrusion cut. They are
872 // separated by composite sketch feature
874 int aNbSubs = aComposite->numberOfSubs();
875 for (int aSub = 0; aSub < aNbSubs && !isSub; aSub++) {
876 isSub = isSubOfComposite(theObject, aComposite->subFeature(aSub));
883 //**************************************************************
884 ResultPtr firstResult(const ObjectPtr& theObject)
886 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
887 if (!aResult.get()) {
888 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
890 aResult = aFeature->firstResult();
895 //**************************************************************
896 bool isFeatureOfResult(const FeaturePtr& theFeature, const std::string& theGroupOfResult)
898 bool isResult = false;
900 if (!theFeature->data()->isValid())
903 ResultPtr aFirstResult = theFeature->firstResult();
904 if (!aFirstResult.get())
907 return aFirstResult->groupName() == theGroupOfResult;
910 //**************************************************************
911 bool hasModuleDocumentFeature(const std::set<FeaturePtr>& theFeatures)
913 bool aFoundModuleDocumentObject = false;
914 DocumentPtr aModuleDoc = ModelAPI_Session::get()->moduleDocument();
916 std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(), aLast = theFeatures.end();
917 for (; anIt != aLast && !aFoundModuleDocumentObject; anIt++) {
918 FeaturePtr aFeature = *anIt;
919 ResultPtr aResult = ModuleBase_Tools::firstResult(aFeature);
920 if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group())
922 aFoundModuleDocumentObject = aFeature->document() == aModuleDoc;
925 return aFoundModuleDocumentObject;
928 //**************************************************************
929 bool askToDelete(const std::set<FeaturePtr> theFeatures,
930 const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
932 std::set<FeaturePtr>& theReferencesToDelete,
933 const std::string& thePrefixInfo)
935 QString aNotActivatedDocWrn;
936 std::string aNotActivatedNames;
937 if (!ModelAPI_Tools::allDocumentsActivated(aNotActivatedNames)) {
938 if (ModuleBase_Tools::hasModuleDocumentFeature(theFeatures))
939 aNotActivatedDocWrn =
940 QObject::tr("Selected objects can be used in Part documents which are not loaded:%1.\n")
941 .arg(aNotActivatedNames.c_str());
944 std::set<FeaturePtr> aFeaturesRefsTo;
945 std::set<FeaturePtr> aFeaturesRefsToParameter;
946 std::set<FeaturePtr> aParameterFeatures;
947 QStringList aPartFeatureNames;
948 std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
949 aLast = theFeatures.end();
950 // separate features to references to parameter features and references to others
951 for (; anIt != aLast; anIt++) {
952 FeaturePtr aFeature = *anIt;
953 if (theReferences.find(aFeature) == theReferences.end())
956 if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
957 aPartFeatureNames.append(aFeature->name().c_str());
959 std::set<FeaturePtr> aRefFeatures;
960 std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
961 std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
962 for (; aRefIt != aRefLast; aRefIt++) {
963 FeaturePtr aRefFeature = *aRefIt;
964 if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
965 aRefFeatures.find(aRefFeature) == aRefFeatures.end()) // it is not added
966 aRefFeatures.insert(aRefFeature);
969 if (isFeatureOfResult(aFeature, ModelAPI_ResultParameter::group())) {
970 aFeaturesRefsToParameter.insert(aRefFeatures.begin(), aRefFeatures.end());
971 aParameterFeatures.insert(aFeature);
974 theReferencesToDelete.insert(aRefFeatures.begin(), aRefFeatures.end());
978 std::set<FeaturePtr> aFeaturesRefsToParameterOnly;
979 anIt = aFeaturesRefsToParameter.begin();
980 aLast = aFeaturesRefsToParameter.end();
981 // separate features to references to parameter features and references to others
982 QStringList aParamFeatureNames;
983 for (; anIt != aLast; anIt++) {
984 FeaturePtr aFeature = *anIt;
985 if (theReferencesToDelete.find(aFeature) == theReferencesToDelete.end()) {
986 aFeaturesRefsToParameterOnly.insert(aFeature);
987 aParamFeatureNames.append(aFeature->name().c_str());
990 aParamFeatureNames.sort();
991 QStringList anOtherFeatureNames;
992 anIt = theReferencesToDelete.begin();
993 aLast = theReferencesToDelete.end();
994 for (; anIt != aLast; anIt++) {
995 FeaturePtr aFeature = *anIt;
996 if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
997 aPartFeatureNames.append(aFeature->name().c_str());
999 anOtherFeatureNames.append(aFeature->name().c_str());
1001 aPartFeatureNames.sort();
1002 anOtherFeatureNames.sort();
1004 bool aCanReplaceParameters = !aFeaturesRefsToParameterOnly.empty();
1006 QMessageBox aMessageBox(theParent);
1007 aMessageBox.setWindowTitle(QObject::tr("Delete features"));
1008 aMessageBox.setIcon(QMessageBox::Warning);
1009 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1010 aMessageBox.setDefaultButton(QMessageBox::No);
1013 if (!thePrefixInfo.empty())
1014 aText = thePrefixInfo.c_str();
1015 QString aSep = ", ";
1016 if (!aPartFeatureNames.empty()) {
1017 aText += QString(QObject::tr("The following parts will be deleted: %1.\n"))
1018 .arg(aPartFeatureNames.join(aSep));
1020 if (!aNotActivatedDocWrn.isEmpty())
1021 aText += aNotActivatedDocWrn;
1022 if (!anOtherFeatureNames.empty()) {
1023 const char* aMsg = "Features are used in the following features: %1.\nThese "
1024 "features will be deleted.\n";
1025 aText += QString(QObject::tr(aMsg))
1026 .arg(anOtherFeatureNames.join(aSep));
1028 if (!aParamFeatureNames.empty()) {
1029 const char* aMsg = "Parameters are used directly and through a sequence "
1030 "of dependencies in the following features: %1.\nThese features will "
1031 "be deleted.\nOr parameters could be replaced by their values.\n";
1032 aText += QString(QObject::tr(aMsg))
1033 .arg(aParamFeatureNames.join(aSep));
1034 QPushButton *aReplaceButton =
1035 aMessageBox.addButton(QObject::tr("Replace"), QMessageBox::ActionRole);
1038 if (!aText.isEmpty()) {
1039 aText += "Would you like to continue?";
1040 aMessageBox.setText(aText);
1042 QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1044 if (aButtonRole == QMessageBox::NoRole)
1047 if (aButtonRole == QMessageBox::ActionRole) {
1048 foreach (FeaturePtr aObj, aParameterFeatures)
1049 ModelAPI_ReplaceParameterMessage::send(aObj, 0);
1052 theReferencesToDelete.insert(aFeaturesRefsToParameterOnly.begin(),
1053 aFeaturesRefsToParameterOnly.end());
1058 //**************************************************************
1059 void convertToFeatures(const QObjectPtrList& theObjects, std::set<FeaturePtr>& theFeatures)
1061 QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1062 for(; anIt != aLast; anIt++) {
1063 ObjectPtr anObject = *anIt;
1064 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1065 // for parameter result, use the corresponded reature to be removed
1066 if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1067 aFeature = ModelAPI_Feature::feature(anObject);
1070 theFeatures.insert(aFeature);
1074 //**************************************************************
1075 void convertToFolders(const QObjectPtrList& theObjects,
1076 std::set<FolderPtr>& theFolders)
1078 QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1079 for(; anIt != aLast; anIt++) {
1080 ObjectPtr anObject = *anIt;
1081 FolderPtr aFeature = std::dynamic_pointer_cast<ModelAPI_Folder>(anObject);
1083 theFolders.insert(aFeature);
1088 //**************************************************************
1089 QString translate(const Events_InfoMessage& theMessage)
1093 if (!theMessage.empty()) {
1094 std::string aStr = Config_Translator::translate(theMessage);
1095 if (!aStr.empty()) {
1096 std::string aCodec = Config_Translator::codec(theMessage);
1097 aMessage = QTextCodec::codecForName(aCodec.c_str())->toUnicode(aStr.c_str());
1104 QString translate(const std::string& theContext, const std::string& theMessage)
1108 if (!theMessage.empty()) {
1109 std::string aStr = Config_Translator::translate(theContext, theMessage);
1110 if (!aStr.empty()) {
1111 std::string aCodec = Config_Translator::codec(theContext);
1112 aMessage = QTextCodec::codecForName(aCodec.c_str())->toUnicode(aStr.c_str());
1119 void setPointBallHighlighting(AIS_Shape* theAIS)
1121 static Handle(Image_AlienPixMap) aPixMap;
1122 if(aPixMap.IsNull()) {
1123 // Load icon for the presentation
1125 char* anEnv = getenv("SHAPER_ROOT_DIR");
1127 aFile = std::string(anEnv) +
1128 FSEP + "share" + FSEP + "salome" + FSEP + "resources" + FSEP + "shaper";
1130 anEnv = getenv("OPENPARTS_ROOT_DIR");
1132 aFile = std::string(anEnv) + FSEP + "resources";
1136 static const std::string aMarkerName = "marker_dot.png";
1137 aFile += aMarkerName;
1138 aPixMap = new Image_AlienPixMap();
1139 if(!aPixMap->Load(aFile.c_str())) {
1140 // The icon for constraint is not found
1141 static const std::string aMsg =
1142 "Error: Point market not found by path: \"" + aFile + "\". Falling back.";
1143 //Events_InfoMessage("ModuleBase_Tools::setPointBallHighlighting", aMsg).send();
1147 Handle(Graphic3d_AspectMarker3d) anAspect;
1148 Handle(Prs3d_Drawer) aDrawer = theAIS->DynamicHilightAttributes();
1149 if (aDrawer.IsNull()) {
1150 if (ModuleBase_IViewer::DefaultHighlightDrawer.IsNull())
1152 aDrawer = new Prs3d_Drawer(*ModuleBase_IViewer::DefaultHighlightDrawer);
1153 if (!aDrawer->HasOwnPointAspect()) {
1154 aDrawer->SetPointAspect(new Prs3d_PointAspect(Aspect_TOM_BALL, Quantity_NOC_BLACK, 2.0));
1157 if(aDrawer->HasOwnPointAspect()) {
1158 Handle(Prs3d_PointAspect) aPntAspect = aDrawer->PointAspect();
1159 if(aPixMap->IsEmpty()) {
1160 anAspect = aPntAspect->Aspect();
1161 anAspect->SetType(Aspect_TOM_BALL);
1163 if(aPixMap->Format() == Image_PixMap::ImgGray) {
1164 aPixMap->SetFormat (Image_PixMap::ImgAlpha);
1165 } else if(aPixMap->Format() == Image_PixMap::ImgGrayF) {
1166 aPixMap->SetFormat (Image_PixMap::ImgAlphaF);
1168 anAspect = new Graphic3d_AspectMarker3d(aPixMap);
1169 aPntAspect->SetAspect(anAspect);
1171 aDrawer->SetPointAspect(aPntAspect);
1172 theAIS->SetDynamicHilightAttributes(aDrawer);
1176 FeaturePtr createParameter(const QString& theText)
1178 FeaturePtr aParameter;
1179 QStringList aList = theText.split("=");
1180 if (aList.count() != 2) {
1183 QString aParamName = aList.at(0).trimmed();
1185 if (isNameExist(aParamName, FeaturePtr())) {
1189 if (!ModelAPI_Expression::isVariable(aParamName.toStdString())) {
1193 QString aExpression = aList.at(1).trimmed();
1194 if (aExpression.isEmpty()) {
1198 SessionPtr aMgr = ModelAPI_Session::get();
1199 std::shared_ptr<ModelAPI_Document> aDoc = aMgr->activeDocument();
1201 aParameter = aDoc->addFeature("Parameter");
1202 if (aParameter.get()) {
1203 AttributeStringPtr aNameAttr = aParameter->string("variable");
1204 aNameAttr->setValue(aParamName.toStdString());
1206 AttributeStringPtr aExprAttr = aParameter->string("expression");
1207 aExprAttr->setValue(aExpression.toStdString());
1208 aParameter->execute();
1210 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1211 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
1216 void editParameter(FeaturePtr theParam, const QString& theText)
1218 QStringList aList = theText.split("=");
1219 QString aParamName = aList.at(0).trimmed();
1221 QString aExpression = aList.at(1).trimmed();
1222 if (aExpression.isEmpty()) {
1226 if (isNameExist(aParamName, theParam)) {
1229 AttributeStringPtr aNameAttr = theParam->string("variable");
1230 aNameAttr->setValue(aParamName.toStdString());
1232 AttributeStringPtr aExprAttr = theParam->string("expression");
1233 aExprAttr->setValue(aExpression.toStdString());
1234 theParam->execute();
1236 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
1239 bool isNameExist(const QString& theName, FeaturePtr theIgnoreParameter)
1241 SessionPtr aMgr = ModelAPI_Session::get();
1242 std::shared_ptr<ModelAPI_Document> aDoc = aMgr->activeDocument();
1243 FeaturePtr aParamFeature;
1244 int aNbFeatures = aDoc->numInternalFeatures();
1245 std::string aName = theName.toStdString();
1246 for (int i = 0; i < aNbFeatures; i++) {
1247 aParamFeature = aDoc->internalFeature(i);
1248 if (aParamFeature && aParamFeature->getKind() == "Parameter") {
1249 if ((theIgnoreParameter != aParamFeature) && (aParamFeature->name() == aName))
1256 FeaturePtr findParameter(const QString& theName)
1258 SessionPtr aMgr = ModelAPI_Session::get();
1259 std::shared_ptr<ModelAPI_Document> aDoc = aMgr->activeDocument();
1260 FeaturePtr aParamFeature;
1261 int aNbFeatures = aDoc->numInternalFeatures();
1262 std::string aName = theName.toStdString();
1263 for (int i = 0; i < aNbFeatures; i++) {
1264 aParamFeature = aDoc->internalFeature(i);
1265 if (aParamFeature && aParamFeature->getKind() == "Parameter") {
1266 if (aParamFeature->name() == aName)
1267 return aParamFeature;
1270 return FeaturePtr();
1274 //********************************************************************
1275 std::string generateName(const AttributePtr& theAttribute,
1276 ModuleBase_IWorkshop* theWorkshop)
1279 if (theAttribute.get() != NULL) {
1280 ModuleBase_Operation* anOperation = theWorkshop->currentOperation();
1282 FeaturePtr aFeature = ModelAPI_Feature::feature(theAttribute->owner());
1283 if (aFeature.get()) {
1284 std::string aXmlCfg, aDescription;
1285 theWorkshop->module()->getXMLRepresentation(aFeature->getKind(), aXmlCfg, aDescription);
1287 ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
1288 std::string anAttributeTitle;
1289 aFactory.getAttributeTitle(theAttribute->id(), anAttributeTitle);
1291 std::stringstream aStreamName;
1292 aStreamName << theAttribute->owner()->data()->name() << "/" << anAttributeTitle.c_str();
1293 aName = aStreamName.str();
1299 } // namespace ModuleBase_Tools