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_ResultCompSolid.h>
49 #include <ModelAPI_ResultParameter.h>
50 #include <ModelAPI_Tools.h>
51 #include <ModelAPI_Session.h>
52 #include <ModelAPI_Events.h>
53 #include <ModelAPI_Folder.h>
55 #include <ModelGeomAlgo_Point2D.h>
57 #include <StdSelect_BRepOwner.hxx>
58 #include <TopoDS_Iterator.hxx>
59 #include <AIS_InteractiveContext.hxx>
60 #include <Prs3d_LineAspect.hxx>
61 #include <Prs3d_PlaneAspect.hxx>
63 #include <GeomDataAPI_Point2D.h>
64 #include <Events_InfoMessage.h>
65 #include <GeomAPI_ShapeExplorer.h>
67 #include <Config_PropManager.h>
68 #include <Config_Translator.h>
70 #include <Prs3d_PointAspect.hxx>
71 #include <Graphic3d_AspectMarker3d.hxx>
73 #include <Image_AlienPixMap.hxx>
79 #include <QDoubleSpinBox>
80 #include <QGraphicsDropShadowEffect>
82 #include <QApplication>
83 #include <QMessageBox>
91 #pragma warning(disable : 4996) // for getenv
94 const double tolerance = 1e-7;
95 const double DEFAULT_DEVIATION_COEFFICIENT = 1.e-4;
97 //#define DEBUG_ACTIVATE_WINDOW
98 //#define DEBUG_SET_FOCUS
106 namespace ModuleBase_Tools {
108 //******************************************************************
110 //******************************************************************
112 void adjustMargins(QWidget* theWidget)
116 adjustMargins(theWidget->layout());
119 void adjustMargins(QLayout* theLayout)
123 theLayout->setContentsMargins(2, 5, 2, 5);
124 theLayout->setSpacing(4);
127 void zeroMargins(QWidget* theWidget)
131 zeroMargins(theWidget->layout());
134 void zeroMargins(QLayout* theLayout)
138 theLayout->setContentsMargins(0, 0, 0, 0);
139 theLayout->setSpacing(5);
142 void activateWindow(QWidget* theWidget, const QString& theInfo)
145 theWidget->activateWindow();
149 #ifdef DEBUG_ACTIVATE_WINDOW
150 qDebug(QString("activateWindow: %1").arg(theInfo).toStdString().c_str());
154 void setFocus(QWidget* theWidget, const QString& theInfo)
156 activateWindow(theWidget);
157 theWidget->setFocus();
158 // rectangle of focus is not visible on tool button widgets
159 theWidget->repaint();
160 #ifdef DEBUG_SET_FOCUS
161 qDebug(QString("setFocus: %1").arg(theInfo).toStdString().c_str());
165 void setShadowEffect(QWidget* theWidget, const bool isSetEffect)
168 QGraphicsDropShadowEffect* aGlowEffect = new QGraphicsDropShadowEffect();
169 aGlowEffect->setOffset(.0);
170 aGlowEffect->setBlurRadius(10.0);
171 aGlowEffect->setColor(QColor(0, 170, 255)); // Light-blue color, #00AAFF
172 theWidget->setGraphicsEffect(aGlowEffect);
175 QGraphicsEffect* anEffect = theWidget->graphicsEffect();
177 anEffect->deleteLater();
178 theWidget->setGraphicsEffect(NULL);
182 QPixmap composite(const QString& theAdditionalIcon, const QString& theIcon)
184 QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
185 QImage anAditional(theAdditionalIcon);
190 int anAddWidth = anAditional.width();
191 int anAddHeight = anAditional.height();
193 int aWidth = anIcon.width();
194 int aHeight = anIcon.height();
196 int aStartWidthPos = aWidth - anAddWidth - 1;
197 int aStartHeightPos = aHeight - anAddHeight - 1;
199 for (int i = 0; i < anAddWidth && i + aStartWidthPos < aWidth; i++)
201 for (int j = 0; j < anAddHeight && j + aStartHeightPos < aHeight; j++)
203 if (qAlpha(anAditional.pixel(i, j)) > 0)
204 anIcon.setPixel(i + aStartWidthPos, j + aStartHeightPos, anAditional.pixel(i, j));
207 return QPixmap::fromImage(anIcon);
210 QPixmap lighter(const QString& theIcon, const int theLighterValue)
212 QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
216 QImage aResult = ModuleBase_IconFactory::loadImage(theIcon);
217 for (int i = 0; i < anIcon.width(); i++)
219 for (int j = 0; j < anIcon.height(); j++)
221 QRgb anRgb = anIcon.pixel(i, j);
222 QColor aPixelColor(qRed(anRgb), qGreen(anRgb), qBlue(anRgb),
223 qAlpha(aResult.pixel(i, j)));
225 QColor aLighterColor = aPixelColor.lighter(theLighterValue);
226 aResult.setPixel(i, j, qRgba(aLighterColor.red(), aLighterColor.green(),
227 aLighterColor.blue(), aLighterColor.alpha()));
230 return QPixmap::fromImage(aResult);
233 void setSpinText(ModuleBase_ParamSpinBox* theSpin, const QString& theText)
235 if (theSpin->text() == theText)
237 // In order to avoid extra text setting because it will
238 // reset cursor position in control
239 bool isBlocked = theSpin->blockSignals(true);
240 theSpin->setText(theText);
241 theSpin->blockSignals(isBlocked);
244 void setSpinValue(QDoubleSpinBox* theSpin, double theValue)
246 if (fabs(theSpin->value() - theValue) < tolerance)
248 bool isBlocked = theSpin->blockSignals(true);
249 theSpin->setValue(theValue);
250 theSpin->blockSignals(isBlocked);
253 void setSpinValue(ModuleBase_ParamSpinBox* theSpin, double theValue)
255 if (fabs(theSpin->value() - theValue) < tolerance)
257 bool isBlocked = theSpin->blockSignals(true);
258 theSpin->setValue(theValue);
259 theSpin->blockSignals(isBlocked);
262 void setSpinText(ModuleBase_ParamIntSpinBox* theSpin, const QString& theText)
264 // In order to avoid extra text setting because it will
265 // reset cursor position in control
266 if (theSpin->text() == theText)
268 bool isBlocked = theSpin->blockSignals(true);
269 theSpin->setText(theText);
270 theSpin->blockSignals(isBlocked);
273 void setSpinValue(ModuleBase_ParamIntSpinBox* theSpin, int theValue)
275 if (theSpin->value() == theValue)
277 bool isBlocked = theSpin->blockSignals(true);
278 theSpin->setValue(theValue);
279 theSpin->blockSignals(isBlocked);
282 QAction* createAction(const QIcon& theIcon, const QString& theText,
283 QObject* theParent, const QObject* theReceiver,
284 const char* theMember, const QString& theToolTip,
285 const QString& theStatusTip)
287 QAction* anAction = new QAction(theIcon, theText, theParent);
288 anAction->setToolTip(theToolTip.isEmpty() ? theText : theToolTip);
289 anAction->setStatusTip(!theStatusTip.isEmpty() ? theStatusTip :
290 (!theToolTip.isEmpty() ? theToolTip : theText));
292 QObject::connect(anAction, SIGNAL(triggered(bool)), theReceiver, theMember);
298 QString objectName(const ObjectPtr& theObj)
303 return theObj->data()->name().c_str();
306 QString objectInfo(const ObjectPtr& theObj, const bool isUseAttributesInfo)
308 QString aFeatureStr = "feature";
312 std::ostringstream aPtrStr;
313 aPtrStr << "[" << theObj.get() << "]";
315 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theObj);
316 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
318 aFeatureStr.append(QString("(result%1)").arg(aPtrStr.str().c_str()).toStdString() .c_str());
319 if (aRes->isDisabled())
320 aFeatureStr.append("[disabled]");
321 if (aRes->isConcealed())
322 aFeatureStr.append("[concealed]");
323 if (ModelAPI_Tools::hasSubResults(aRes))
324 aFeatureStr.append("[hasSubResults]");
326 aFeature = ModelAPI_Feature::feature(aRes);
329 aFeatureStr.append(aPtrStr.str().c_str());
331 if (aFeature.get()) {
332 aFeatureStr.append(QString(": %1").arg(aFeature->getKind().c_str()).toStdString().c_str());
333 if (aFeature->data()->isValid()) {
334 aFeatureStr.append(QString(", name=%1").arg(theObj->data()->name().c_str()).toStdString()
337 if (isUseAttributesInfo) {
338 std::set<std::shared_ptr<ModelAPI_Attribute> > anAttributes;
339 std::string aPointsInfo = ModelGeomAlgo_Point2D::getPontAttributesInfo(aFeature,
340 anAttributes).c_str();
341 if (!aPointsInfo.empty())
342 aFeatureStr.append(QString(", attributes: %1")
343 .arg(aPointsInfo.c_str()).toStdString().c_str());
351 typedef QMap<QString, int> ShapeTypes;
352 static ShapeTypes myShapeTypes;
354 int shapeType(const QString& theType)
356 if (myShapeTypes.count() == 0) {
357 myShapeTypes["compound"] = TopAbs_COMPOUND;
358 myShapeTypes["compounds"] = TopAbs_COMPOUND;
359 myShapeTypes["compsolid"] = TopAbs_COMPSOLID;
360 myShapeTypes["compsolids"] = TopAbs_COMPSOLID;
361 myShapeTypes["solid"] = TopAbs_SOLID;
362 myShapeTypes["solids"] = TopAbs_SOLID;
363 myShapeTypes["shell"] = TopAbs_SHELL;
364 myShapeTypes["shells"] = TopAbs_SHELL;
365 myShapeTypes["face"] = TopAbs_FACE;
366 myShapeTypes["faces"] = TopAbs_FACE;
367 myShapeTypes["wire"] = TopAbs_WIRE;
368 myShapeTypes["wires"] = TopAbs_WIRE;
369 myShapeTypes["edge"] = TopAbs_EDGE;
370 myShapeTypes["edges"] = TopAbs_EDGE;
371 myShapeTypes["vertex"] = TopAbs_VERTEX;
372 myShapeTypes["vertices"] = TopAbs_VERTEX;
373 myShapeTypes["object"] = ModuleBase_ResultPrs::Sel_Result;
374 myShapeTypes["objects"] = ModuleBase_ResultPrs::Sel_Result;
376 QString aType = theType.toLower();
377 if(myShapeTypes.contains(aType))
378 return myShapeTypes[aType];
379 Events_InfoMessage("ModuleBase_Tools", "Shape type defined in XML is not implemented!").send();
383 void checkObjects(const QObjectPtrList& theObjects, bool& hasResult, bool& hasFeature,
384 bool& hasParameter, bool& hasCompositeOwner, bool& hasResultInHistory,
389 hasParameter = false;
390 hasCompositeOwner = false;
391 hasResultInHistory = false;
393 foreach(ObjectPtr aObj, theObjects) {
394 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
395 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
396 FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(aObj);
397 ResultParameterPtr aConstruction = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aResult);
399 hasResult |= (aResult.get() != NULL);
400 hasFeature |= (aFeature.get() != NULL);
401 hasFolder |= (aFolder.get() != NULL);
402 hasParameter |= (aConstruction.get() != NULL);
404 hasCompositeOwner |= (ModelAPI_Tools::compositeOwner(aFeature) != NULL);
406 if (!hasResultInHistory && aResult.get()) {
407 FeaturePtr aFeature = ModelAPI_Feature::feature(aResult);
408 hasResultInHistory = aFeature.get() && aFeature->isInHistory();
411 if (hasFeature && hasResult && hasParameter && hasCompositeOwner && hasFeature)
416 /*bool setDefaultDeviationCoefficient(std::shared_ptr<GeomAPI_Shape> theGeomShape)
418 if (!theGeomShape.get())
420 // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
421 // correction of deviation for them should not influence to the application performance
422 GeomAPI_ShapeExplorer anExp(theGeomShape, GeomAPI_Shape::FACE);
423 bool anEmpty = anExp.empty();
424 return !anExp.more();
427 /*void setDefaultDeviationCoefficient(const std::shared_ptr<ModelAPI_Result>& theResult,
428 const Handle(Prs3d_Drawer)& theDrawer)
430 if (!theResult.get())
432 bool aUseDeviation = false;
434 std::string aResultGroup = theResult->groupName();
435 if (aResultGroup == ModelAPI_ResultConstruction::group())
436 aUseDeviation = true;
437 else if (aResultGroup == ModelAPI_ResultBody::group()) {
438 GeomShapePtr aGeomShape = theResult->shape();
439 if (aGeomShape.get())
440 aUseDeviation = setDefaultDeviationCoefficient(aGeomShape);
443 theDrawer->SetDeviationCoefficient(DEFAULT_DEVIATION_COEFFICIENT);
446 void setDefaultDeviationCoefficient(const TopoDS_Shape& theShape,
447 const Handle(Prs3d_Drawer)& theDrawer)
449 if (theShape.IsNull())
452 std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape());
453 aGeomShape->setImpl(new TopoDS_Shape(theShape));
455 // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
456 // correction of deviation for them should not influence to the application performance
457 GeomAPI_ShapeExplorer anExp(aGeomShape, GeomAPI_Shape::FACE);
458 bool isConstruction = !anExp.more();
462 aDeflection = Config_PropManager::real("Visualization", "construction_deflection");
464 aDeflection = Config_PropManager::real("Visualization", "body_deflection");
466 theDrawer->SetDeviationCoefficient(aDeflection);
469 Quantity_Color color(const std::string& theSection,
470 const std::string& theName)
472 std::vector<int> aColor = Config_PropManager::color(theSection, theName);
473 return Quantity_Color(aColor[0] / 255., aColor[1] / 255., aColor[2] / 255., Quantity_TOC_RGB);
476 ObjectPtr getObject(const AttributePtr& theAttribute)
479 std::string anAttrType = theAttribute->attributeType();
480 if (anAttrType == ModelAPI_AttributeRefAttr::typeId()) {
481 AttributeRefAttrPtr anAttr =
482 std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
483 if (anAttr != NULL && anAttr->isObject())
484 anObject = anAttr->object();
486 if (anAttrType == ModelAPI_AttributeSelection::typeId()) {
487 AttributeSelectionPtr anAttr =
488 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
490 anObject = anAttr->context();
492 if (anAttrType == ModelAPI_AttributeReference::typeId()) {
493 AttributeReferencePtr anAttr =
494 std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
495 if (anAttr.get() != NULL)
496 anObject = anAttr->value();
501 TopAbs_ShapeEnum getCompoundSubType(const TopoDS_Shape& theShape)
503 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
505 // for compounds check sub-shapes: it may be compound of needed type:
506 // Booleans may produce compounds of Solids
507 if (aShapeType == TopAbs_COMPOUND) {
508 for(TopoDS_Iterator aSubs(theShape); aSubs.More(); aSubs.Next()) {
509 if (!aSubs.Value().IsNull()) {
510 TopAbs_ShapeEnum aSubType = aSubs.Value().ShapeType();
511 if (aSubType == TopAbs_COMPOUND) { // compound of compound(s)
512 aShapeType = TopAbs_COMPOUND;
515 if (aShapeType == TopAbs_COMPOUND) {
516 aShapeType = aSubType;
517 } else if (aShapeType != aSubType) { // compound of shapes of different types
518 aShapeType = TopAbs_COMPOUND;
527 TopoDS_Shape getSelectedShape(const std::shared_ptr<ModuleBase_ViewerPrs>& thePrs)
529 if (thePrs->shape().get())
530 return thePrs->shape()->impl<TopoDS_Shape>();
532 Handle(StdSelect_BRepOwner) anOwner = Handle(StdSelect_BRepOwner)::DownCast(thePrs->owner());
533 if (!anOwner.IsNull())
534 return anOwner->Shape();
536 return TopoDS_Shape();
539 void getParameters(QStringList& theParameters)
541 theParameters.clear();
543 SessionPtr aSession = ModelAPI_Session::get();
544 std::list<DocumentPtr> aDocList;
545 DocumentPtr anActiveDocument = aSession->activeDocument();
546 DocumentPtr aRootDocument = aSession->moduleDocument();
547 aDocList.push_back(anActiveDocument);
548 if (anActiveDocument != aRootDocument) {
549 aDocList.push_back(aRootDocument);
551 std::string aGroupId = ModelAPI_ResultParameter::group();
552 for(std::list<DocumentPtr>::const_iterator it = aDocList.begin(); it != aDocList.end(); ++it) {
553 DocumentPtr aDocument = *it;
554 int aSize = aDocument->size(aGroupId);
555 for (int i = 0; i < aSize; i++) {
556 ObjectPtr anObject = aDocument->object(aGroupId, i);
557 std::string aParameterName = anObject->data()->name();
558 theParameters.append(aParameterName.c_str());
563 std::string findGreedAttribute(ModuleBase_IWorkshop* theWorkshop,
564 const FeaturePtr& theFeature)
566 std::string anAttributeId;
568 std::string aXmlCfg, aDescription;
569 theWorkshop->module()->getXMLRepresentation(theFeature->getKind(), aXmlCfg, aDescription);
571 ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
572 std::string anAttributeTitle;
573 aFactory.getGreedAttribute(anAttributeId);
575 return anAttributeId;
578 bool hasObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
579 const std::shared_ptr<GeomAPI_Shape>& theShape,
580 ModuleBase_IWorkshop* theWorkshop,
581 const bool theTemporarily)
583 bool aHasObject = false;
584 if (!theAttribute.get())
587 std::string aType = theAttribute->attributeType();
588 if (aType == ModelAPI_AttributeReference::typeId()) {
589 AttributeReferencePtr aRef =
590 std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
591 ObjectPtr aObject = aRef->value();
592 aHasObject = aObject && aObject->isSame(theObject);
593 //if (!(aObject && aObject->isSame(theObject))) {
594 // aRef->setValue(theObject);
596 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
597 AttributeRefAttrPtr aRefAttr =
598 std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
600 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
601 if (anAttribute.get()) {
602 //aRefAttr->setAttr(anAttribute);
605 ObjectPtr aObject = aRefAttr->object();
606 aHasObject = aObject && aObject->isSame(theObject);
607 //if (!(aObject && aObject->isSame(theObject))) {
608 // aRefAttr->setObject(theObject);
611 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
612 /*AttributeSelectionPtr aSelectAttr =
613 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
614 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
615 if (aSelectAttr.get() != NULL) {
616 aSelectAttr->setValue(aResult, theShape, theTemporarily);
619 if (aType == ModelAPI_AttributeSelectionList::typeId()) {
620 AttributeSelectionListPtr aSelectionListAttr =
621 std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
622 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
623 aHasObject = aSelectionListAttr->isInList(aResult, theShape, theTemporarily);
625 else if (aType == ModelAPI_AttributeRefList::typeId()) {
626 AttributeRefListPtr aRefListAttr =
627 std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
628 aHasObject = aRefListAttr->isInList(theObject);
629 //if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
630 // aRefListAttr->append(theObject);
632 else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
633 AttributeRefAttrListPtr aRefAttrListAttr =
634 std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
635 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
637 if (anAttribute.get()) {
638 aHasObject = aRefAttrListAttr->isInList(anAttribute);
639 //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
640 // aRefAttrListAttr->append(anAttribute);
643 aHasObject = aRefAttrListAttr->isInList(theObject);
644 //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
645 // aRefAttrListAttr->append(theObject);
651 bool setObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
652 const GeomShapePtr& theShape, ModuleBase_IWorkshop* theWorkshop,
653 const bool theTemporarily, const bool theCheckIfAttributeHasObject)
655 if (!theAttribute.get())
659 std::string aType = theAttribute->attributeType();
660 if (aType == ModelAPI_AttributeReference::typeId()) {
661 AttributeReferencePtr aRef =
662 std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
663 ObjectPtr aObject = aRef->value();
664 if (!(aObject && aObject->isSame(theObject))) {
665 aRef->setValue(theObject);
667 } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
668 AttributeRefAttrPtr aRefAttr =
669 std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
671 AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
672 if (anAttribute.get())
673 aRefAttr->setAttr(anAttribute);
675 ObjectPtr aObject = aRefAttr->object();
676 if (!(aObject && aObject->isSame(theObject))) {
677 aRefAttr->setObject(theObject);
680 } else if (aType == ModelAPI_AttributeSelection::typeId()) {
681 AttributeSelectionPtr aSelectAttr =
682 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
683 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
684 if (aSelectAttr.get() != NULL) {
685 aSelectAttr->setValue(aResult, theShape, theTemporarily);
688 if (aType == ModelAPI_AttributeSelectionList::typeId()) {
689 AttributeSelectionListPtr aSelectionListAttr =
690 std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
691 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
692 if (!theCheckIfAttributeHasObject ||
693 !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
694 aSelectionListAttr->append(aResult, 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 = 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 (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
996 aPartFeatureNames.append(aFeature->name().c_str());
998 anOtherFeatureNames.append(aFeature->name().c_str());
1000 aPartFeatureNames.sort();
1001 anOtherFeatureNames.sort();
1003 bool aCanReplaceParameters = !aFeaturesRefsToParameterOnly.empty();
1005 QMessageBox aMessageBox(theParent);
1006 aMessageBox.setWindowTitle(QObject::tr("Delete features"));
1007 aMessageBox.setIcon(QMessageBox::Warning);
1008 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1009 aMessageBox.setDefaultButton(QMessageBox::No);
1012 if (!thePrefixInfo.empty())
1013 aText = thePrefixInfo.c_str();
1014 QString aSep = ", ";
1015 if (!aPartFeatureNames.empty()) {
1016 aText += QString(QObject::tr("The following parts will be deleted: %1.\n"))
1017 .arg(aPartFeatureNames.join(aSep));
1019 if (!aNotActivatedDocWrn.isEmpty())
1020 aText += aNotActivatedDocWrn;
1021 if (!anOtherFeatureNames.empty()) {
1022 const char* aMsg = "Features are used in the following features: %1.\nThese "
1023 "features will be deleted.\n";
1024 aText += QString(QObject::tr(aMsg))
1025 .arg(anOtherFeatureNames.join(aSep));
1027 if (!aParamFeatureNames.empty()) {
1028 const char* aMsg = "Parameters are used directly and through a sequence "
1029 "of dependencies in the following features: %1.\nThese features will "
1030 "be deleted.\nOr parameters could be replaced by their values.\n";
1031 aText += QString(QObject::tr(aMsg))
1032 .arg(aParamFeatureNames.join(aSep));
1033 QPushButton *aReplaceButton =
1034 aMessageBox.addButton(QObject::tr("Replace"), QMessageBox::ActionRole);
1037 if (!aText.isEmpty()) {
1038 aText += "Would you like to continue?";
1039 aMessageBox.setText(aText);
1041 QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1043 if (aButtonRole == QMessageBox::NoRole)
1046 if (aButtonRole == QMessageBox::ActionRole) {
1047 foreach (FeaturePtr aObj, aParameterFeatures)
1048 ModelAPI_ReplaceParameterMessage::send(aObj, 0);
1051 theReferencesToDelete.insert(aFeaturesRefsToParameterOnly.begin(),
1052 aFeaturesRefsToParameterOnly.end());
1057 //**************************************************************
1058 void convertToFeatures(const QObjectPtrList& theObjects, std::set<FeaturePtr>& theFeatures)
1060 QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1061 for(; anIt != aLast; anIt++) {
1062 ObjectPtr anObject = *anIt;
1063 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1064 // for parameter result, use the corresponded reature to be removed
1065 if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1066 aFeature = ModelAPI_Feature::feature(anObject);
1069 theFeatures.insert(aFeature);
1073 //**************************************************************
1074 void convertToFolders(const QObjectPtrList& theObjects,
1075 std::set<FolderPtr>& theFolders)
1077 QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1078 for(; anIt != aLast; anIt++) {
1079 ObjectPtr anObject = *anIt;
1080 FolderPtr aFeature = std::dynamic_pointer_cast<ModelAPI_Folder>(anObject);
1082 theFolders.insert(aFeature);
1087 //**************************************************************
1088 QString translate(const Events_InfoMessage& theMessage)
1092 if (!theMessage.empty()) {
1093 std::string aStr = Config_Translator::translate(theMessage);
1094 if (!aStr.empty()) {
1095 std::string aCodec = Config_Translator::codec(theMessage);
1096 aMessage = QTextCodec::codecForName(aCodec.c_str())->toUnicode(aStr.c_str());
1103 QString translate(const std::string& theContext, const std::string& theMessage)
1107 if (!theMessage.empty()) {
1108 std::string aStr = Config_Translator::translate(theContext, theMessage);
1109 if (!aStr.empty()) {
1110 std::string aCodec = Config_Translator::codec(theContext);
1111 aMessage = QTextCodec::codecForName(aCodec.c_str())->toUnicode(aStr.c_str());
1118 void setPointBallHighlighting(AIS_Shape* theAIS)
1120 static Handle(Image_AlienPixMap) aPixMap;
1121 if(aPixMap.IsNull()) {
1122 // Load icon for the presentation
1124 char* anEnv = getenv("SHAPER_ROOT_DIR");
1126 aFile = std::string(anEnv) +
1127 FSEP + "share" + FSEP + "salome" + FSEP + "resources" + FSEP + "shaper";
1129 anEnv = getenv("OPENPARTS_ROOT_DIR");
1131 aFile = std::string(anEnv) + FSEP + "resources";
1135 static const std::string aMarkerName = "marker_dot.png";
1136 aFile += aMarkerName;
1137 aPixMap = new Image_AlienPixMap();
1138 if(!aPixMap->Load(aFile.c_str())) {
1139 // The icon for constraint is not found
1140 static const std::string aMsg =
1141 "Error: Point market not found by path: \"" + aFile + "\". Falling back.";
1142 //Events_InfoMessage("ModuleBase_Tools::setPointBallHighlighting", aMsg).send();
1146 Handle(Graphic3d_AspectMarker3d) anAspect;
1147 Handle(Prs3d_Drawer) aDrawer = theAIS->DynamicHilightAttributes();
1148 if (aDrawer.IsNull()) {
1149 if (ModuleBase_IViewer::DefaultHighlightDrawer.IsNull())
1151 aDrawer = new Prs3d_Drawer(*ModuleBase_IViewer::DefaultHighlightDrawer);
1152 if (!aDrawer->HasOwnPointAspect()) {
1153 aDrawer->SetPointAspect(new Prs3d_PointAspect(Aspect_TOM_BALL, Quantity_NOC_BLACK, 2.0));
1156 if(aDrawer->HasOwnPointAspect()) {
1157 Handle(Prs3d_PointAspect) aPntAspect = aDrawer->PointAspect();
1158 if(aPixMap->IsEmpty()) {
1159 anAspect = aPntAspect->Aspect();
1160 anAspect->SetType(Aspect_TOM_BALL);
1162 if(aPixMap->Format() == Image_PixMap::ImgGray) {
1163 aPixMap->SetFormat (Image_PixMap::ImgAlpha);
1164 } else if(aPixMap->Format() == Image_PixMap::ImgGrayF) {
1165 aPixMap->SetFormat (Image_PixMap::ImgAlphaF);
1167 anAspect = new Graphic3d_AspectMarker3d(aPixMap);
1168 aPntAspect->SetAspect(anAspect);
1170 aDrawer->SetPointAspect(aPntAspect);
1171 theAIS->SetDynamicHilightAttributes(aDrawer);
1175 FeaturePtr createParameter(const QString& theText)
1177 FeaturePtr aParameter;
1178 QStringList aList = theText.split("=");
1179 if (aList.count() != 2) {
1182 QString aParamName = aList.at(0).trimmed();
1184 if (isNameExist(aParamName, FeaturePtr())) {
1188 if (!ModelAPI_Expression::isVariable(aParamName.toStdString())) {
1192 QString aExpression = aList.at(1).trimmed();
1193 if (aExpression.isEmpty()) {
1197 SessionPtr aMgr = ModelAPI_Session::get();
1198 std::shared_ptr<ModelAPI_Document> aDoc = aMgr->activeDocument();
1200 aParameter = aDoc->addFeature("Parameter");
1201 if (aParameter.get()) {
1202 AttributeStringPtr aNameAttr = aParameter->string("variable");
1203 aNameAttr->setValue(aParamName.toStdString());
1205 AttributeStringPtr aExprAttr = aParameter->string("expression");
1206 aExprAttr->setValue(aExpression.toStdString());
1207 aParameter->execute();
1209 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1210 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
1215 void editParameter(FeaturePtr theParam, const QString& theText)
1217 QStringList aList = theText.split("=");
1218 QString aParamName = aList.at(0).trimmed();
1220 QString aExpression = aList.at(1).trimmed();
1221 if (aExpression.isEmpty()) {
1225 if (isNameExist(aParamName, theParam)) {
1228 AttributeStringPtr aNameAttr = theParam->string("variable");
1229 aNameAttr->setValue(aParamName.toStdString());
1231 AttributeStringPtr aExprAttr = theParam->string("expression");
1232 aExprAttr->setValue(aExpression.toStdString());
1233 theParam->execute();
1235 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
1238 bool isNameExist(const QString& theName, FeaturePtr theIgnoreParameter)
1240 SessionPtr aMgr = ModelAPI_Session::get();
1241 std::shared_ptr<ModelAPI_Document> aDoc = aMgr->activeDocument();
1242 FeaturePtr aParamFeature;
1243 int aNbFeatures = aDoc->numInternalFeatures();
1244 std::string aName = theName.toStdString();
1245 for (int i = 0; i < aNbFeatures; i++) {
1246 aParamFeature = aDoc->internalFeature(i);
1247 if (aParamFeature && aParamFeature->getKind() == "Parameter") {
1248 if ((theIgnoreParameter != aParamFeature) && (aParamFeature->name() == aName))
1255 FeaturePtr findParameter(const QString& theName)
1257 SessionPtr aMgr = ModelAPI_Session::get();
1258 std::shared_ptr<ModelAPI_Document> aDoc = aMgr->activeDocument();
1259 FeaturePtr aParamFeature;
1260 int aNbFeatures = aDoc->numInternalFeatures();
1261 std::string aName = theName.toStdString();
1262 for (int i = 0; i < aNbFeatures; i++) {
1263 aParamFeature = aDoc->internalFeature(i);
1264 if (aParamFeature && aParamFeature->getKind() == "Parameter") {
1265 if (aParamFeature->name() == aName)
1266 return aParamFeature;
1269 return FeaturePtr();
1273 //********************************************************************
1274 std::string generateName(const AttributePtr& theAttribute,
1275 ModuleBase_IWorkshop* theWorkshop)
1278 if (theAttribute.get() != NULL) {
1279 ModuleBase_Operation* anOperation = theWorkshop->currentOperation();
1281 FeaturePtr aFeature = ModelAPI_Feature::feature(theAttribute->owner());
1282 if (aFeature.get()) {
1283 std::string aXmlCfg, aDescription;
1284 theWorkshop->module()->getXMLRepresentation(aFeature->getKind(), aXmlCfg, aDescription);
1286 ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
1287 std::string anAttributeTitle;
1288 aFactory.getAttributeTitle(theAttribute->id(), anAttributeTitle);
1290 std::stringstream aStreamName;
1291 aStreamName << theAttribute->owner()->data()->name() << "/" << anAttributeTitle.c_str();
1292 aName = aStreamName.str();
1298 } // namespace ModuleBase_Tools