1 // Copyright (C) 2014-2019 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 email : webmaster.salome@opencascade.com
20 #include "ModuleBase_Tools.h"
22 #include <ModuleBase_ParamIntSpinBox.h>
23 #include <ModuleBase_ParamSpinBox.h>
24 #include <ModuleBase_WidgetFactory.h>
25 #include <ModuleBase_IWorkshop.h>
26 #include <ModuleBase_IModule.h>
27 #include <ModuleBase_IViewer.h>
28 #include <ModuleBase_IconFactory.h>
29 #include <ModuleBase_ResultPrs.h>
30 #include <ModuleBase_ViewerPrs.h>
32 #include <ModelAPI_Attribute.h>
33 #include <ModelAPI_AttributeRefAttr.h>
34 #include <ModelAPI_AttributeReference.h>
35 #include <ModelAPI_AttributeSelection.h>
36 #include <ModelAPI_AttributeSelectionList.h>
37 #include <ModelAPI_AttributeRefList.h>
38 #include <ModelAPI_AttributeRefAttrList.h>
39 #include <ModelAPI_ResultPart.h>
40 #include <ModelAPI_ResultConstruction.h>
41 #include <ModelAPI_AttributeString.h>
42 #include <ModelAPI_Expression.h>
43 #include <Events_Loop.h>
45 #include <ModelAPI_Data.h>
46 #include <ModelAPI_Result.h>
47 #include <ModelAPI_ResultParameter.h>
48 #include <ModelAPI_Tools.h>
49 #include <ModelAPI_Session.h>
50 #include <ModelAPI_Events.h>
51 #include <ModelAPI_Folder.h>
53 #include <ModelGeomAlgo_Point2D.h>
55 #include <StdSelect_BRepOwner.hxx>
56 #include <TopoDS_Iterator.hxx>
57 #include <AIS_InteractiveContext.hxx>
58 #include <Prs3d_LineAspect.hxx>
59 #include <Prs3d_PlaneAspect.hxx>
61 #include <GeomDataAPI_Point2D.h>
62 #include <Events_InfoMessage.h>
63 #include <GeomAPI_ShapeExplorer.h>
65 #include <Config_PropManager.h>
66 #include <Config_Translator.h>
68 #include <Prs3d_PointAspect.hxx>
69 #include <Graphic3d_AspectMarker3d.hxx>
71 #include <Image_AlienPixMap.hxx>
77 #include <QDoubleSpinBox>
78 #include <QGraphicsDropShadowEffect>
80 #include <QApplication>
81 #include <QMessageBox>
89 #pragma warning(disable : 4996) // for getenv
92 const double tolerance = 1e-7;
93 const double DEFAULT_DEVIATION_COEFFICIENT = 1.e-4;
95 //#define DEBUG_ACTIVATE_WINDOW
96 //#define DEBUG_SET_FOCUS
104 namespace ModuleBase_Tools {
106 //******************************************************************
108 //******************************************************************
110 void adjustMargins(QWidget* theWidget)
114 adjustMargins(theWidget->layout());
117 void adjustMargins(QLayout* theLayout)
121 theLayout->setContentsMargins(2, 5, 2, 5);
122 theLayout->setSpacing(4);
125 void zeroMargins(QWidget* theWidget)
129 zeroMargins(theWidget->layout());
132 void zeroMargins(QLayout* theLayout)
136 theLayout->setContentsMargins(0, 0, 0, 0);
137 theLayout->setSpacing(5);
140 void activateWindow(QWidget* theWidget, const QString& theInfo)
143 theWidget->activateWindow();
147 #ifdef DEBUG_ACTIVATE_WINDOW
148 qDebug(QString("activateWindow: %1").arg(theInfo).toStdString().c_str());
152 void setFocus(QWidget* theWidget, const QString& theInfo)
154 activateWindow(theWidget);
155 theWidget->setFocus();
156 // rectangle of focus is not visible on tool button widgets
157 theWidget->repaint();
158 #ifdef DEBUG_SET_FOCUS
159 qDebug(QString("setFocus: %1").arg(theInfo).toStdString().c_str());
163 void setShadowEffect(QWidget* theWidget, const bool isSetEffect)
166 QGraphicsDropShadowEffect* aGlowEffect = new QGraphicsDropShadowEffect();
167 aGlowEffect->setOffset(.0);
168 aGlowEffect->setBlurRadius(10.0);
169 aGlowEffect->setColor(QColor(0, 170, 255)); // Light-blue color, #00AAFF
170 theWidget->setGraphicsEffect(aGlowEffect);
173 QGraphicsEffect* anEffect = theWidget->graphicsEffect();
175 anEffect->deleteLater();
176 theWidget->setGraphicsEffect(NULL);
180 QPixmap composite(const QString& theAdditionalIcon, const QString& theIcon)
182 QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
183 QImage anAditional(theAdditionalIcon);
184 return composite(anAditional, anIcon);
187 QPixmap composite(const QImage& theAdditionalIcon, QImage& theIcon)
189 if (theIcon.isNull())
192 int anAddWidth = theAdditionalIcon.width();
193 int anAddHeight = theAdditionalIcon.height();
195 int aWidth = theIcon.width();
196 int aHeight = theIcon.height();
198 int aStartWidthPos = aWidth - anAddWidth;
199 int aStartHeightPos = aHeight - anAddHeight;
201 for (int i = 0; i < anAddWidth && i + aStartWidthPos < aWidth; i++)
203 for (int j = 0; j < anAddHeight && j + aStartHeightPos < aHeight; j++)
205 if (qAlpha(theAdditionalIcon.pixel(i, j)) > 0)
206 theIcon.setPixel(i + aStartWidthPos, j + aStartHeightPos, theAdditionalIcon.pixel(i, j));
209 return QPixmap::fromImage(theIcon);
212 QPixmap lighter(const QString& theIcon, const int theLighterValue)
214 QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
218 QImage aResult = ModuleBase_IconFactory::loadImage(theIcon);
219 for (int i = 0; i < anIcon.width(); i++)
221 for (int j = 0; j < anIcon.height(); j++)
223 QRgb anRgb = anIcon.pixel(i, j);
224 QColor aPixelColor(qRed(anRgb), qGreen(anRgb), qBlue(anRgb),
225 qAlpha(aResult.pixel(i, j)));
227 QColor aLighterColor = aPixelColor.lighter(theLighterValue);
228 aResult.setPixel(i, j, qRgba(aLighterColor.red(), aLighterColor.green(),
229 aLighterColor.blue(), aLighterColor.alpha()));
232 return QPixmap::fromImage(aResult);
235 void setSpinText(ModuleBase_ParamSpinBox* theSpin, const QString& theText)
237 if (theSpin->text() == theText)
239 // In order to avoid extra text setting because it will
240 // reset cursor position in control
241 bool isBlocked = theSpin->blockSignals(true);
242 theSpin->setText(theText);
243 theSpin->blockSignals(isBlocked);
246 void setSpinValue(QDoubleSpinBox* theSpin, double theValue)
248 if (fabs(theSpin->value() - theValue) < tolerance)
250 bool isBlocked = theSpin->blockSignals(true);
251 theSpin->setValue(theValue);
252 theSpin->blockSignals(isBlocked);
255 void setSpinValue(ModuleBase_ParamSpinBox* theSpin, double theValue)
257 if (fabs(theSpin->value() - theValue) < tolerance)
259 bool isBlocked = theSpin->blockSignals(true);
260 theSpin->setValue(theValue);
261 theSpin->blockSignals(isBlocked);
264 void setSpinText(ModuleBase_ParamIntSpinBox* theSpin, const QString& theText)
266 // In order to avoid extra text setting because it will
267 // reset cursor position in control
268 if (theSpin->text() == theText)
270 bool isBlocked = theSpin->blockSignals(true);
271 theSpin->setText(theText);
272 theSpin->blockSignals(isBlocked);
275 void setSpinValue(ModuleBase_ParamIntSpinBox* theSpin, int theValue)
277 if (theSpin->value() == theValue)
279 bool isBlocked = theSpin->blockSignals(true);
280 theSpin->setValue(theValue);
281 theSpin->blockSignals(isBlocked);
284 QAction* createAction(const QIcon& theIcon, const QString& theText,
285 QObject* theParent, const QObject* theReceiver,
286 const char* theMember, const QString& theToolTip,
287 const QString& theStatusTip)
289 QAction* anAction = new QAction(theIcon, theText, theParent);
290 anAction->setToolTip(theToolTip.isEmpty() ? theText : theToolTip);
291 anAction->setStatusTip(!theStatusTip.isEmpty() ? theStatusTip :
292 (!theToolTip.isEmpty() ? theToolTip : theText));
294 QObject::connect(anAction, SIGNAL(triggered(bool)), theReceiver, theMember);
300 QString objectName(const ObjectPtr& theObj)
305 return theObj->data()->name().c_str();
308 QString objectInfo(const ObjectPtr& theObj, const bool isUseAttributesInfo)
310 QString aFeatureStr = "feature";
314 std::ostringstream aPtrStr;
315 aPtrStr << "[" << theObj.get() << "]";
317 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theObj);
318 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
320 aFeatureStr.append(QString("(result%1)").arg(aPtrStr.str().c_str()).toStdString() .c_str());
321 if (aRes->isDisabled())
322 aFeatureStr.append("[disabled]");
323 if (aRes->isConcealed())
324 aFeatureStr.append("[concealed]");
325 if (ModelAPI_Tools::hasSubResults(aRes))
326 aFeatureStr.append("[hasSubResults]");
328 aFeature = ModelAPI_Feature::feature(aRes);
331 aFeatureStr.append(aPtrStr.str().c_str());
333 if (aFeature.get()) {
334 aFeatureStr.append(QString(": %1").arg(aFeature->getKind().c_str()).toStdString().c_str());
335 if (aFeature->data()->isValid()) {
336 aFeatureStr.append(QString(", name=%1").arg(theObj->data()->name().c_str()).toStdString()
339 if (isUseAttributesInfo) {
340 std::set<std::shared_ptr<ModelAPI_Attribute> > anAttributes;
341 std::string aPointsInfo = ModelGeomAlgo_Point2D::getPontAttributesInfo(aFeature,
342 anAttributes).c_str();
343 if (!aPointsInfo.empty())
344 aFeatureStr.append(QString(", attributes: %1")
345 .arg(aPointsInfo.c_str()).toStdString().c_str());
353 typedef QMap<QString, int> ShapeTypes;
354 static ShapeTypes myShapeTypes;
356 int shapeType(const QString& theType)
358 if (myShapeTypes.count() == 0) {
359 myShapeTypes["compound"] = TopAbs_COMPOUND;
360 myShapeTypes["compounds"] = TopAbs_COMPOUND;
361 myShapeTypes["compsolid"] = TopAbs_COMPSOLID;
362 myShapeTypes["compsolids"] = TopAbs_COMPSOLID;
363 myShapeTypes["solid"] = TopAbs_SOLID;
364 myShapeTypes["solids"] = TopAbs_SOLID;
365 myShapeTypes["shell"] = TopAbs_SHELL;
366 myShapeTypes["shells"] = TopAbs_SHELL;
367 myShapeTypes["face"] = TopAbs_FACE;
368 myShapeTypes["faces"] = TopAbs_FACE;
369 myShapeTypes["wire"] = TopAbs_WIRE;
370 myShapeTypes["wires"] = TopAbs_WIRE;
371 myShapeTypes["edge"] = TopAbs_EDGE;
372 myShapeTypes["edges"] = TopAbs_EDGE;
373 myShapeTypes["vertex"] = TopAbs_VERTEX;
374 myShapeTypes["vertices"] = TopAbs_VERTEX;
375 myShapeTypes["object"] = ModuleBase_ResultPrs::Sel_Result;
376 myShapeTypes["objects"] = ModuleBase_ResultPrs::Sel_Result;
378 QString aType = theType.toLower();
379 if(myShapeTypes.contains(aType))
380 return myShapeTypes[aType];
381 Events_InfoMessage("ModuleBase_Tools", "Shape type defined in XML is not implemented!").send();
385 void checkObjects(const QObjectPtrList& theObjects, bool& hasResult, bool& hasFeature,
386 bool& hasParameter, bool& hasCompositeOwner, bool& hasResultInHistory,
391 hasParameter = false;
392 hasCompositeOwner = false;
393 hasResultInHistory = false;
395 foreach(ObjectPtr aObj, theObjects) {
396 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
397 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
398 FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(aObj);
399 ResultParameterPtr aConstruction = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aResult);
401 hasResult |= (aResult.get() != NULL);
402 hasFeature |= (aFeature.get() != NULL);
403 hasFolder |= (aFolder.get() != NULL);
404 hasParameter |= (aConstruction.get() != NULL);
406 hasCompositeOwner |= (ModelAPI_Tools::compositeOwner(aFeature) != NULL);
408 if (!hasResultInHistory && aResult.get()) {
409 FeaturePtr aFeature = ModelAPI_Feature::feature(aResult);
410 hasResultInHistory = aFeature.get() && aFeature->isInHistory();
413 if (hasFeature && hasResult && hasParameter && hasCompositeOwner && hasFeature)
418 /*bool setDefaultDeviationCoefficient(std::shared_ptr<GeomAPI_Shape> theGeomShape)
420 if (!theGeomShape.get())
422 // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
423 // correction of deviation for them should not influence to the application performance
424 GeomAPI_ShapeExplorer anExp(theGeomShape, GeomAPI_Shape::FACE);
425 bool anEmpty = anExp.empty();
426 return !anExp.more();
429 /*void setDefaultDeviationCoefficient(const std::shared_ptr<ModelAPI_Result>& theResult,
430 const Handle(Prs3d_Drawer)& theDrawer)
432 if (!theResult.get())
434 bool aUseDeviation = false;
436 std::string aResultGroup = theResult->groupName();
437 if (aResultGroup == ModelAPI_ResultConstruction::group())
438 aUseDeviation = true;
439 else if (aResultGroup == ModelAPI_ResultBody::group()) {
440 GeomShapePtr aGeomShape = theResult->shape();
441 if (aGeomShape.get())
442 aUseDeviation = setDefaultDeviationCoefficient(aGeomShape);
445 theDrawer->SetDeviationCoefficient(DEFAULT_DEVIATION_COEFFICIENT);
448 void setDefaultDeviationCoefficient(const TopoDS_Shape& theShape,
449 const Handle(Prs3d_Drawer)& theDrawer)
451 if (theShape.IsNull())
454 std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape());
455 aGeomShape->setImpl(new TopoDS_Shape(theShape));
457 // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
458 // correction of deviation for them should not influence to the application performance
459 GeomAPI_ShapeExplorer anExp(aGeomShape, GeomAPI_Shape::FACE);
460 bool isConstruction = !anExp.more();
464 aDeflection = Config_PropManager::real("Visualization", "construction_deflection");
466 aDeflection = Config_PropManager::real("Visualization", "body_deflection");
468 theDrawer->SetDeviationCoefficient(aDeflection);
471 Quantity_Color color(const std::string& theSection,
472 const std::string& theName)
474 std::vector<int> aColor = Config_PropManager::color(theSection, theName);
475 return Quantity_Color(aColor[0] / 255., aColor[1] / 255., aColor[2] / 255., Quantity_TOC_RGB);
478 ObjectPtr getObject(const AttributePtr& theAttribute)
481 std::string anAttrType = theAttribute->attributeType();
482 if (anAttrType == ModelAPI_AttributeRefAttr::typeId()) {
483 AttributeRefAttrPtr anAttr =
484 std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
485 if (anAttr != NULL && anAttr->isObject())
486 anObject = anAttr->object();
488 if (anAttrType == ModelAPI_AttributeSelection::typeId()) {
489 AttributeSelectionPtr anAttr =
490 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
492 anObject = anAttr->context();
494 if (anAttrType == ModelAPI_AttributeReference::typeId()) {
495 AttributeReferencePtr anAttr =
496 std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
497 if (anAttr.get() != NULL)
498 anObject = anAttr->value();
503 TopAbs_ShapeEnum getCompoundSubType(const TopoDS_Shape& theShape)
505 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
507 // for compounds check sub-shapes: it may be compound of needed type:
508 // Booleans may produce compounds of Solids
509 if (aShapeType == TopAbs_COMPOUND) {
510 for(TopoDS_Iterator aSubs(theShape); aSubs.More(); aSubs.Next()) {
511 if (!aSubs.Value().IsNull()) {
512 TopAbs_ShapeEnum aSubType = aSubs.Value().ShapeType();
513 if (aSubType == TopAbs_COMPOUND) { // compound of compound(s)
514 aShapeType = TopAbs_COMPOUND;
517 if (aShapeType == TopAbs_COMPOUND) {
518 aShapeType = aSubType;
519 } else if (aShapeType != aSubType) { // compound of shapes of different types
520 aShapeType = TopAbs_COMPOUND;
529 TopoDS_Shape getSelectedShape(const std::shared_ptr<ModuleBase_ViewerPrs>& thePrs)
531 if (thePrs->shape().get())
532 return thePrs->shape()->impl<TopoDS_Shape>();
534 Handle(StdSelect_BRepOwner) anOwner = Handle(StdSelect_BRepOwner)::DownCast(thePrs->owner());
535 if (!anOwner.IsNull())
536 return anOwner->Shape();
538 return TopoDS_Shape();
541 void getParameters(QStringList& theParameters)
543 theParameters.clear();
545 SessionPtr aSession = ModelAPI_Session::get();
546 std::list<DocumentPtr> aDocList;
547 DocumentPtr anActiveDocument = aSession->activeDocument();
548 DocumentPtr aRootDocument = aSession->moduleDocument();
549 aDocList.push_back(anActiveDocument);
550 if (anActiveDocument != aRootDocument) {
551 aDocList.push_back(aRootDocument);
553 std::string aGroupId = ModelAPI_ResultParameter::group();
554 for(std::list<DocumentPtr>::const_iterator it = aDocList.begin(); it != aDocList.end(); ++it) {
555 DocumentPtr aDocument = *it;
556 int aSize = aDocument->size(aGroupId);
557 for (int i = 0; i < aSize; i++) {
558 ObjectPtr anObject = aDocument->object(aGroupId, i);
559 std::string aParameterName = anObject->data()->name();
560 theParameters.append(aParameterName.c_str());
565 std::string findGreedAttribute(ModuleBase_IWorkshop* theWorkshop,
566 const FeaturePtr& theFeature)
568 std::string anAttributeId;
570 std::string aXmlCfg, aDescription;
571 theWorkshop->module()->getXMLRepresentation(theFeature->getKind(), aXmlCfg, aDescription);
573 ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
574 std::string anAttributeTitle;
575 aFactory.getGreedAttribute(anAttributeId);
577 return anAttributeId;
580 bool hasObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
581 const std::shared_ptr<GeomAPI_Shape>& theShape,
582 ModuleBase_IWorkshop* theWorkshop,
583 const bool theTemporarily)
585 bool aHasObject = false;
586 if (!theAttribute.get())
589 std::string aType = theAttribute->attributeType();
590 if (aType == ModelAPI_AttributeReference::typeId()) {
591 AttributeReferencePtr aRef =
592 std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
593 ObjectPtr aObject = aRef->value();
594 aHasObject = aObject && aObject->isSame(theObject);
595 //if (!(aObject && aObject->isSame(theObject))) {
596 // aRef->setValue(theObject);
598 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
599 AttributeRefAttrPtr aRefAttr =
600 std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
602 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
603 if (anAttribute.get()) {
604 //aRefAttr->setAttr(anAttribute);
607 ObjectPtr aObject = aRefAttr->object();
608 aHasObject = aObject && aObject->isSame(theObject);
609 //if (!(aObject && aObject->isSame(theObject))) {
610 // aRefAttr->setObject(theObject);
613 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
614 /*AttributeSelectionPtr aSelectAttr =
615 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
616 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
617 if (aSelectAttr.get() != NULL) {
618 aSelectAttr->setValue(aResult, theShape, theTemporarily);
621 if (aType == ModelAPI_AttributeSelectionList::typeId()) {
622 AttributeSelectionListPtr aSelectionListAttr =
623 std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
624 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
625 aHasObject = aSelectionListAttr->isInList(aResult, theShape, theTemporarily);
627 else if (aType == ModelAPI_AttributeRefList::typeId()) {
628 AttributeRefListPtr aRefListAttr =
629 std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
630 aHasObject = aRefListAttr->isInList(theObject);
631 //if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
632 // aRefListAttr->append(theObject);
634 else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
635 AttributeRefAttrListPtr aRefAttrListAttr =
636 std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
637 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
639 if (anAttribute.get()) {
640 aHasObject = aRefAttrListAttr->isInList(anAttribute);
641 //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
642 // aRefAttrListAttr->append(anAttribute);
645 aHasObject = aRefAttrListAttr->isInList(theObject);
646 //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
647 // aRefAttrListAttr->append(theObject);
653 bool setObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
654 const GeomShapePtr& theShape, ModuleBase_IWorkshop* theWorkshop,
655 const bool theTemporarily, const bool theCheckIfAttributeHasObject)
657 if (!theAttribute.get())
661 std::string aType = theAttribute->attributeType();
662 if (aType == ModelAPI_AttributeReference::typeId()) {
663 AttributeReferencePtr aRef =
664 std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
665 ObjectPtr aObject = aRef->value();
666 if (!(aObject && aObject->isSame(theObject))) {
667 aRef->setValue(theObject);
669 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
670 AttributeRefAttrPtr aRefAttr =
671 std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
673 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
674 if (anAttribute.get())
675 aRefAttr->setAttr(anAttribute);
677 ObjectPtr aObject = aRefAttr->object();
678 if (!(aObject && aObject->isSame(theObject))) {
679 aRefAttr->setObject(theObject);
682 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
683 AttributeSelectionPtr aSelectAttr =
684 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
685 if (aSelectAttr.get() != NULL) {
686 aSelectAttr->setValue(theObject, theShape, theTemporarily);
689 if (aType == ModelAPI_AttributeSelectionList::typeId()) {
690 AttributeSelectionListPtr aSelectionListAttr =
691 std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
692 if (!theCheckIfAttributeHasObject ||
693 !aSelectionListAttr->isInList(theObject, theShape, theTemporarily))
694 aSelectionListAttr->append(theObject, theShape, theTemporarily);
696 else if (aType == ModelAPI_AttributeRefList::typeId()) {
697 AttributeRefListPtr aRefListAttr =
698 std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
699 if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject)) {
701 aRefListAttr->append(theObject);
706 else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
707 AttributeRefAttrListPtr aRefAttrListAttr =
708 std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
709 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
711 if (anAttribute.get()) {
712 if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
713 aRefAttrListAttr->append(anAttribute);
716 if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject)) {
718 aRefAttrListAttr->append(theObject);
727 GeomShapePtr getShape(const AttributePtr& theAttribute, ModuleBase_IWorkshop* theWorkshop)
730 if (!theAttribute.get())
733 std::string aType = theAttribute->attributeType();
734 if (aType == ModelAPI_AttributeReference::typeId()) {
735 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
736 AttributeRefAttrPtr aRefAttr =
737 std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
738 if (aRefAttr.get() && !aRefAttr->isObject()) {
739 AttributePtr anAttribute = aRefAttr->attr();
740 aShape = theWorkshop->module()->findShape(anAttribute);
742 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
743 AttributeSelectionPtr aSelectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>
745 aShape = aSelectAttr->value();
747 else // Geom2D point processing
748 aShape = theWorkshop->module()->findShape(theAttribute);
752 void flushUpdated(ObjectPtr theObject)
754 blockUpdateViewer(true);
756 // Fix the problem of not previewed results of constraints applied. Flush Create/Delete
757 // (for the sketch result) to start processing of the sketch in the solver.
758 // TODO: these flushes should be moved in a separate method provided by Model
759 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
760 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
761 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
763 blockUpdateViewer(false);
766 void blockUpdateViewer(const bool theValue)
768 // the viewer update should be blocked in order to avoid the temporary feature content
769 // when the solver processes the feature, the redisplay message can be flushed
770 // what caused the display in the viewer preliminary states of object
771 // e.g. fillet feature, angle value change
772 std::shared_ptr<Events_Message> aMsg;
774 aMsg = std::shared_ptr<Events_Message>(
775 new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)));
778 // the viewer update should be unblocked
779 aMsg = std::shared_ptr<Events_Message>(
780 new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)));
782 Events_Loop::loop()->send(aMsg);
785 QString wrapTextByWords(const QString& theValue, QWidget* theWidget,
786 int theMaxLineInPixels)
788 static QFontMetrics tfm(theWidget ? theWidget->font() : QApplication::font());
789 static qreal phi = 2.618;
791 QRect aBounds = tfm.boundingRect(theValue);
792 if(aBounds.width() <= theMaxLineInPixels)
795 qreal s = aBounds.width() * aBounds.height();
796 qreal aGoldWidth = sqrt(s*phi);
798 QStringList aWords = theValue.split(" ", QString::SkipEmptyParts);
800 int n = aWords.count();
802 for (int i = 0; i < n; i++) {
803 QString aLineExt = i == 0 ? aWords[i] : aLine + " " + aWords[i];
804 qreal anWidthNonExt = tfm.boundingRect(aLine).width();
805 qreal anWidthExt = tfm.boundingRect(aLineExt).width();
806 qreal aDeltaNonExt = fabs(anWidthNonExt-aGoldWidth);
807 qreal aDeltaExt = fabs(anWidthExt-aGoldWidth);
808 if(aDeltaNonExt < aDeltaExt) {
810 aLines.append(aLine);
818 aLines.append(aLine);
820 QString aResult = aLines.join("\n");
824 //**************************************************************
825 QLocale doubleLocale()
827 // VSR 01/07/2010: Disable thousands separator for spin box
828 // (to avoid inconsistency of double-2-string and string-2-double conversion)
830 aLocale.setNumberOptions(aLocale.numberOptions() |
831 QLocale::OmitGroupSeparator |
832 QLocale::RejectGroupSeparator);
836 //**************************************************************
837 void refsToFeatureInFeatureDocument(const ObjectPtr& theObject,
838 std::set<FeaturePtr>& theRefFeatures)
840 FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
841 if (aFeature.get()) {
842 DocumentPtr aFeatureDoc = aFeature->document();
843 // 1. find references in the current document
844 aFeatureDoc->refsToFeature(aFeature, theRefFeatures, false);
849 //**************************************************************
850 /*bool isSubOfComposite(const ObjectPtr& theObject)
853 std::set<FeaturePtr> aRefFeatures;
854 refsToFeatureInFeatureDocument(theObject, aRefFeatures);
855 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
856 aLast = aRefFeatures.end();
857 for (; anIt != aLast && !isSub; anIt++) {
858 isSub = isSubOfComposite(theObject, *anIt);
863 //**************************************************************
864 /*bool isSubOfComposite(const ObjectPtr& theObject, const FeaturePtr& theFeature)
867 CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
868 if (aComposite.get()) {
869 isSub = aComposite->isSub(theObject);
870 // the recursive is possible, the parameters are sketch circle and extrusion cut. They are
871 // separated by composite sketch feature
873 int aNbSubs = aComposite->numberOfSubs();
874 for (int aSub = 0; aSub < aNbSubs && !isSub; aSub++) {
875 isSub = isSubOfComposite(theObject, aComposite->subFeature(aSub));
882 //**************************************************************
883 ResultPtr firstResult(const ObjectPtr& theObject)
885 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
886 if (!aResult.get()) {
887 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
889 aResult = aFeature->firstResult();
894 //**************************************************************
895 bool isFeatureOfResult(const FeaturePtr& theFeature, const std::string& theGroupOfResult)
897 bool isResult = false;
899 if (!theFeature->data()->isValid())
902 ResultPtr aFirstResult = theFeature->firstResult();
903 if (!aFirstResult.get())
906 return aFirstResult->groupName() == theGroupOfResult;
909 //**************************************************************
910 bool hasModuleDocumentFeature(const std::set<FeaturePtr>& theFeatures)
912 bool aFoundModuleDocumentObject = false;
913 DocumentPtr aModuleDoc = ModelAPI_Session::get()->moduleDocument();
915 std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(), aLast = theFeatures.end();
916 for (; anIt != aLast && !aFoundModuleDocumentObject; anIt++) {
917 FeaturePtr aFeature = *anIt;
918 ResultPtr aResult = ModuleBase_Tools::firstResult(aFeature);
919 if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group())
921 aFoundModuleDocumentObject = aFeature->document() == aModuleDoc;
924 return aFoundModuleDocumentObject;
927 //**************************************************************
928 bool askToDelete(const std::set<FeaturePtr> theFeatures,
929 const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
931 std::set<FeaturePtr>& theReferencesToDelete,
932 const std::string& thePrefixInfo)
934 QString aNotActivatedDocWrn;
935 std::string aNotActivatedNames;
936 if (!ModelAPI_Tools::allDocumentsActivated(aNotActivatedNames)) {
937 if (ModuleBase_Tools::hasModuleDocumentFeature(theFeatures))
938 aNotActivatedDocWrn =
939 QObject::tr("Selected objects can be used in Part documents which are not loaded:%1.\n")
940 .arg(aNotActivatedNames.c_str());
943 std::set<FeaturePtr> aFeaturesRefsTo;
944 std::set<FeaturePtr> aFeaturesRefsToParameter;
945 std::set<FeaturePtr> aParameterFeatures;
946 QStringList aPartFeatureNames;
947 std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
948 aLast = theFeatures.end();
949 // separate features to references to parameter features and references to others
950 for (; anIt != aLast; anIt++) {
951 FeaturePtr aFeature = *anIt;
952 if (theReferences.find(aFeature) == theReferences.end())
955 if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
956 aPartFeatureNames.append(aFeature->name().c_str());
958 std::set<FeaturePtr> aRefFeatures;
959 std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
960 std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
961 for (; aRefIt != aRefLast; aRefIt++) {
962 FeaturePtr aRefFeature = *aRefIt;
963 if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
964 aRefFeatures.find(aRefFeature) == aRefFeatures.end()) // it is not added
965 aRefFeatures.insert(aRefFeature);
968 if (isFeatureOfResult(aFeature, ModelAPI_ResultParameter::group())) {
969 aFeaturesRefsToParameter.insert(aRefFeatures.begin(), aRefFeatures.end());
970 aParameterFeatures.insert(aFeature);
973 theReferencesToDelete.insert(aRefFeatures.begin(), aRefFeatures.end());
977 std::set<FeaturePtr> aFeaturesRefsToParameterOnly;
978 anIt = aFeaturesRefsToParameter.begin();
979 aLast = aFeaturesRefsToParameter.end();
980 // separate features to references to parameter features and references to others
981 QStringList aParamFeatureNames;
982 for (; anIt != aLast; anIt++) {
983 FeaturePtr aFeature = *anIt;
984 if (theReferencesToDelete.find(aFeature) == theReferencesToDelete.end()) {
985 aFeaturesRefsToParameterOnly.insert(aFeature);
986 aParamFeatureNames.append(aFeature->name().c_str());
989 aParamFeatureNames.sort();
990 QStringList anOtherFeatureNames;
991 anIt = theReferencesToDelete.begin();
992 aLast = theReferencesToDelete.end();
993 for (; anIt != aLast; anIt++) {
994 FeaturePtr aFeature = *anIt;
995 if (aFeature->getKind() == "RemoveResults")
996 continue; // skip the remove results feature mentioning: result will be removed anyway
997 if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
998 aPartFeatureNames.append(aFeature->name().c_str());
1000 anOtherFeatureNames.append(aFeature->name().c_str());
1002 aPartFeatureNames.sort();
1003 anOtherFeatureNames.sort();
1005 bool aCanReplaceParameters = !aFeaturesRefsToParameterOnly.empty();
1007 QMessageBox aMessageBox(theParent);
1008 aMessageBox.setWindowTitle(QObject::tr("Delete features"));
1009 aMessageBox.setIcon(QMessageBox::Warning);
1010 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1011 aMessageBox.setDefaultButton(QMessageBox::No);
1014 if (!thePrefixInfo.empty())
1015 aText = thePrefixInfo.c_str();
1016 QString aSep = ", ";
1017 if (!aPartFeatureNames.empty()) {
1018 aText += QString(QObject::tr("The following parts will be deleted: %1.\n"))
1019 .arg(aPartFeatureNames.join(aSep));
1021 if (!aNotActivatedDocWrn.isEmpty())
1022 aText += aNotActivatedDocWrn;
1023 if (!anOtherFeatureNames.empty()) {
1024 const char* aMsg = "Features are used in the following features: %1.\nThese "
1025 "features will be deleted.\n";
1026 aText += QString(QObject::tr(aMsg))
1027 .arg(anOtherFeatureNames.join(aSep));
1029 if (!aParamFeatureNames.empty()) {
1030 const char* aMsg = "Parameters are used directly and through a sequence "
1031 "of dependencies in the following features: %1.\nThese features will "
1032 "be deleted.\nOr parameters could be replaced by their values.\n";
1033 aText += QString(QObject::tr(aMsg))
1034 .arg(aParamFeatureNames.join(aSep));
1035 QPushButton *aReplaceButton =
1036 aMessageBox.addButton(QObject::tr("Replace"), QMessageBox::ActionRole);
1039 if (!aText.isEmpty()) {
1040 aText += "Would you like to continue?";
1041 aMessageBox.setText(aText);
1043 QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1045 if (aButtonRole == QMessageBox::NoRole)
1048 if (aButtonRole == QMessageBox::ActionRole) {
1049 foreach (FeaturePtr aObj, aParameterFeatures)
1050 ModelAPI_ReplaceParameterMessage::send(aObj, 0);
1053 theReferencesToDelete.insert(aFeaturesRefsToParameterOnly.begin(),
1054 aFeaturesRefsToParameterOnly.end());
1059 //**************************************************************
1060 void convertToFeatures(const QObjectPtrList& theObjects, std::set<FeaturePtr>& theFeatures)
1062 QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1063 for(; anIt != aLast; anIt++) {
1064 ObjectPtr anObject = *anIt;
1065 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1066 // for parameter result, use the corresponded reature to be removed
1067 if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1068 aFeature = ModelAPI_Feature::feature(anObject);
1071 theFeatures.insert(aFeature);
1075 //**************************************************************
1076 void convertToFolders(const QObjectPtrList& theObjects,
1077 std::set<FolderPtr>& theFolders)
1079 QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1080 for(; anIt != aLast; anIt++) {
1081 ObjectPtr anObject = *anIt;
1082 FolderPtr aFeature = std::dynamic_pointer_cast<ModelAPI_Folder>(anObject);
1084 theFolders.insert(aFeature);
1089 //**************************************************************
1090 QString translate(const Events_InfoMessage& theMessage)
1094 if (!theMessage.empty()) {
1095 std::string aStr = Config_Translator::translate(theMessage);
1096 if (!aStr.empty()) {
1097 std::string aCodec = Config_Translator::codec(theMessage);
1098 aMessage = QTextCodec::codecForName(aCodec.c_str())->toUnicode(aStr.c_str());
1105 QString translate(const std::string& theContext, const std::string& theMessage)
1109 if (!theMessage.empty()) {
1110 std::string aStr = Config_Translator::translate(theContext, theMessage);
1111 if (!aStr.empty()) {
1112 std::string aCodec = Config_Translator::codec(theContext);
1113 aMessage = QTextCodec::codecForName(aCodec.c_str())->toUnicode(aStr.c_str());
1120 void setPointBallHighlighting(AIS_Shape* theAIS)
1122 static Handle(Image_AlienPixMap) aPixMap;
1123 if(aPixMap.IsNull()) {
1124 // Load icon for the presentation
1126 char* anEnv = getenv("SHAPER_ROOT_DIR");
1128 aFile = std::string(anEnv) +
1129 FSEP + "share" + FSEP + "salome" + FSEP + "resources" + FSEP + "shaper";
1131 anEnv = getenv("OPENPARTS_ROOT_DIR");
1133 aFile = std::string(anEnv) + FSEP + "resources";
1137 static const std::string aMarkerName = "marker_dot.png";
1138 aFile += aMarkerName;
1139 aPixMap = new Image_AlienPixMap();
1140 if(!aPixMap->Load(aFile.c_str())) {
1141 // The icon for constraint is not found
1142 static const std::string aMsg =
1143 "Error: Point market not found by path: \"" + aFile + "\". Falling back.";
1144 //Events_InfoMessage("ModuleBase_Tools::setPointBallHighlighting", aMsg).send();
1148 Handle(Graphic3d_AspectMarker3d) anAspect;
1149 Handle(Prs3d_Drawer) aDrawer = theAIS->DynamicHilightAttributes();
1150 if (aDrawer.IsNull()) {
1151 if (ModuleBase_IViewer::DefaultHighlightDrawer.IsNull())
1153 aDrawer = new Prs3d_Drawer(*ModuleBase_IViewer::DefaultHighlightDrawer);
1154 if (!aDrawer->HasOwnPointAspect()) {
1155 aDrawer->SetPointAspect(new Prs3d_PointAspect(Aspect_TOM_BALL, Quantity_NOC_BLACK, 2.0));
1158 if(aDrawer->HasOwnPointAspect()) {
1159 Handle(Prs3d_PointAspect) aPntAspect = aDrawer->PointAspect();
1160 if(aPixMap->IsEmpty()) {
1161 anAspect = aPntAspect->Aspect();
1162 anAspect->SetType(Aspect_TOM_BALL);
1164 if(aPixMap->Format() == Image_PixMap::ImgGray) {
1165 aPixMap->SetFormat (Image_PixMap::ImgAlpha);
1166 } else if(aPixMap->Format() == Image_PixMap::ImgGrayF) {
1167 aPixMap->SetFormat (Image_PixMap::ImgAlphaF);
1169 anAspect = new Graphic3d_AspectMarker3d(aPixMap);
1170 aPntAspect->SetAspect(anAspect);
1172 aDrawer->SetPointAspect(aPntAspect);
1173 theAIS->SetDynamicHilightAttributes(aDrawer);
1177 FeaturePtr createParameter(const QString& theText)
1179 FeaturePtr aParameter;
1180 QStringList aList = theText.split("=");
1181 if (aList.count() != 2) {
1184 QString aParamName = aList.at(0).trimmed();
1186 if (isNameExist(aParamName, FeaturePtr())) {
1190 if (!ModelAPI_Expression::isVariable(aParamName.toStdString())) {
1194 QString aExpression = aList.at(1).trimmed();
1195 if (aExpression.isEmpty()) {
1199 SessionPtr aMgr = ModelAPI_Session::get();
1200 std::shared_ptr<ModelAPI_Document> aDoc = aMgr->activeDocument();
1202 aParameter = aDoc->addFeature("Parameter");
1203 if (aParameter.get()) {
1204 AttributeStringPtr aNameAttr = aParameter->string("variable");
1205 aNameAttr->setValue(aParamName.toStdString());
1207 AttributeStringPtr aExprAttr = aParameter->string("expression");
1208 aExprAttr->setValue(aExpression.toStdString());
1209 aParameter->execute();
1211 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1212 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
1217 void editParameter(FeaturePtr theParam, const QString& theText)
1219 QStringList aList = theText.split("=");
1220 QString aParamName = aList.at(0).trimmed();
1222 QString aExpression = aList.at(1).trimmed();
1223 if (aExpression.isEmpty()) {
1227 if (isNameExist(aParamName, theParam)) {
1230 AttributeStringPtr aNameAttr = theParam->string("variable");
1231 aNameAttr->setValue(aParamName.toStdString());
1233 AttributeStringPtr aExprAttr = theParam->string("expression");
1234 aExprAttr->setValue(aExpression.toStdString());
1235 theParam->execute();
1237 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
1240 bool isNameExist(const QString& theName, FeaturePtr theIgnoreParameter)
1242 SessionPtr aMgr = ModelAPI_Session::get();
1243 std::shared_ptr<ModelAPI_Document> aDoc = aMgr->activeDocument();
1244 FeaturePtr aParamFeature;
1245 int aNbFeatures = aDoc->numInternalFeatures();
1246 std::string aName = theName.toStdString();
1247 for (int i = 0; i < aNbFeatures; i++) {
1248 aParamFeature = aDoc->internalFeature(i);
1249 if (aParamFeature && aParamFeature->getKind() == "Parameter") {
1250 if ((theIgnoreParameter != aParamFeature) && (aParamFeature->name() == aName))
1257 FeaturePtr findParameter(const QString& theName)
1259 SessionPtr aMgr = ModelAPI_Session::get();
1260 std::shared_ptr<ModelAPI_Document> aDoc = aMgr->activeDocument();
1261 FeaturePtr aParamFeature;
1262 int aNbFeatures = aDoc->numInternalFeatures();
1263 std::string aName = theName.toStdString();
1264 for (int i = 0; i < aNbFeatures; i++) {
1265 aParamFeature = aDoc->internalFeature(i);
1266 if (aParamFeature && aParamFeature->getKind() == "Parameter") {
1267 if (aParamFeature->name() == aName)
1268 return aParamFeature;
1271 return FeaturePtr();
1275 //********************************************************************
1276 std::string generateName(const AttributePtr& theAttribute,
1277 ModuleBase_IWorkshop* theWorkshop)
1280 if (theAttribute.get() != NULL) {
1281 ModuleBase_Operation* anOperation = theWorkshop->currentOperation();
1283 FeaturePtr aFeature = ModelAPI_Feature::feature(theAttribute->owner());
1284 if (aFeature.get()) {
1285 std::string aXmlCfg, aDescription;
1286 theWorkshop->module()->getXMLRepresentation(aFeature->getKind(), aXmlCfg, aDescription);
1288 ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
1289 std::string anAttributeTitle;
1290 aFactory.getAttributeTitle(theAttribute->id(), anAttributeTitle);
1292 std::stringstream aStreamName;
1293 aStreamName << theAttribute->owner()->data()->name() << "/" << anAttributeTitle.c_str();
1294 aName = aStreamName.str();
1300 } // namespace ModuleBase_Tools