]> SALOME platform Git repositories - modules/shaper.git/blob - src/ModuleBase/ModuleBase_Tools.cpp
Salome HOME
Cover debug information with _DEBUG definition.
[modules/shaper.git] / src / ModuleBase / ModuleBase_Tools.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        ModuleBase_Tools.cpp
4 // Created:     11 July 2014
5 // Author:      Vitaly Smetannikov
6
7 #include "ModuleBase_Tools.h"
8
9 #include <ModuleBase_ParamIntSpinBox.h>
10 #include <ModuleBase_ParamSpinBox.h>
11 #include <ModuleBase_WidgetFactory.h>
12 #include <ModuleBase_IWorkshop.h>
13 #include <ModuleBase_IModule.h>
14 #include <ModuleBase_IconFactory.h>
15 #include <ModuleBase_ResultPrs.h>
16
17 #include <ModelAPI_Attribute.h>
18 #include <ModelAPI_AttributeRefAttr.h>
19 #include <ModelAPI_AttributeReference.h>
20 #include <ModelAPI_AttributeSelection.h>
21 #include <ModelAPI_AttributeSelectionList.h>
22 #include <ModelAPI_AttributeRefList.h>
23 #include <ModelAPI_AttributeRefAttrList.h>
24 #include <ModelAPI_ResultPart.h>
25 #include <ModelAPI_ResultConstruction.h>
26 #include <Events_Loop.h>
27
28 #include <ModelAPI_Data.h>
29 #include <ModelAPI_Result.h>
30 #include <ModelAPI_ResultCompSolid.h>
31 #include <ModelAPI_ResultParameter.h>
32 #include <ModelAPI_Tools.h>
33 #include <ModelAPI_Session.h>
34 #include <ModelAPI_Events.h>
35
36 #include <ModelGeomAlgo_Point2D.h>
37
38 #include <TopoDS_Iterator.hxx>
39
40 #include <GeomDataAPI_Point2D.h>
41 #include <Events_InfoMessage.h>
42 #include <GeomAPI_ShapeExplorer.h>
43
44 #include <Config_PropManager.h>
45 #include <Config_Translator.h>
46
47 #include <Prs3d_PointAspect.hxx>
48 #include <Graphic3d_AspectMarker3d.hxx>
49
50 #include <Image_AlienPixMap.hxx>
51
52 #include <QWidget>
53 #include <QLayout>
54 #include <QPainter>
55 #include <QBitmap>
56 #include <QDoubleSpinBox>
57 #include <QGraphicsDropShadowEffect>
58 #include <QColor>
59 #include <QApplication>
60 #include <QMessageBox>
61 #include <QAction>
62 #include <QTextCodec>
63
64 #include <sstream>
65 #include <string>
66
67 #ifdef WIN32
68 #pragma warning(disable : 4996) // for getenv
69 #endif
70
71 const double tolerance = 1e-7;
72 const double DEFAULT_DEVIATION_COEFFICIENT = 1.e-4;
73
74 //#define DEBUG_ACTIVATE_WINDOW
75 //#define DEBUG_SET_FOCUS
76
77 #ifdef WIN32
78 # define FSEP "\\"
79 #else
80 # define FSEP "/"
81 #endif
82
83 namespace ModuleBase_Tools {
84
85 //******************************************************************
86
87 //******************************************************************
88
89 void adjustMargins(QWidget* theWidget)
90 {
91   if(!theWidget)
92     return;
93   adjustMargins(theWidget->layout());
94 }
95
96 void adjustMargins(QLayout* theLayout)
97 {
98   if(!theLayout)
99     return;
100   theLayout->setContentsMargins(2, 5, 2, 5);
101   theLayout->setSpacing(4);
102 }
103
104 void zeroMargins(QWidget* theWidget)
105 {
106   if(!theWidget)
107     return;
108   zeroMargins(theWidget->layout());
109 }
110
111 void zeroMargins(QLayout* theLayout)
112 {
113   if(!theLayout)
114     return;
115   theLayout->setContentsMargins(0, 0, 0, 0);
116   theLayout->setSpacing(5);
117 }
118
119 void activateWindow(QWidget* theWidget, const QString& theInfo)
120 {
121   theWidget->activateWindow();
122
123 #ifdef DEBUG_ACTIVATE_WINDOW
124   qDebug(QString("activateWindow: %1").arg(theInfo).toStdString().c_str());
125 #endif
126 }
127
128 void setFocus(QWidget* theWidget, const QString& theInfo)
129 {
130   theWidget->setFocus();
131
132 #ifdef DEBUG_SET_FOCUS
133   qDebug(QString("setFocus: %1").arg(theInfo).toStdString().c_str());
134 #endif
135 }
136
137 void setShadowEffect(QWidget* theWidget, const bool isSetEffect)
138 {
139   if (isSetEffect) {
140     QGraphicsDropShadowEffect* aGlowEffect = new QGraphicsDropShadowEffect();
141     aGlowEffect->setOffset(.0);
142     aGlowEffect->setBlurRadius(10.0);
143     aGlowEffect->setColor(QColor(0, 170, 255)); // Light-blue color, #00AAFF
144     theWidget->setGraphicsEffect(aGlowEffect);
145   }
146   else {
147     QGraphicsEffect* anEffect = theWidget->graphicsEffect();
148     if(anEffect)
149       anEffect->deleteLater();
150     theWidget->setGraphicsEffect(NULL);
151   }
152 }
153
154 QPixmap composite(const QString& theAdditionalIcon, const QString& theIcon)
155 {
156   QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
157   QImage anAditional(theAdditionalIcon);
158
159   if (anIcon.isNull())
160     return QPixmap();
161
162   int anAddWidth = anAditional.width();
163   int anAddHeight = anAditional.height();
164
165   int aWidth = anIcon.width();
166   int aHeight = anIcon.height();
167
168   int aStartWidthPos = aWidth - anAddWidth - 1;
169   int aStartHeightPos = aHeight - anAddHeight - 1;
170
171   for (int i = 0; i < anAddWidth && i + aStartWidthPos < aWidth; i++)
172   {
173     for (int j = 0; j < anAddHeight && j + aStartHeightPos < aHeight; j++)
174     {
175       if (qAlpha(anAditional.pixel(i, j)) > 0)
176         anIcon.setPixel(i + aStartWidthPos, j + aStartHeightPos, anAditional.pixel(i, j));
177     }
178   }
179   return QPixmap::fromImage(anIcon);
180 }
181
182 QPixmap lighter(const QString& theIcon, const int theLighterValue)
183 {
184   QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
185   if (anIcon.isNull())
186     return QPixmap();
187
188   QImage aResult = ModuleBase_IconFactory::loadImage(theIcon);
189   for (int i = 0; i < anIcon.width(); i++)
190   {
191     for (int j = 0; j < anIcon.height(); j++)
192     {
193       QRgb anRgb = anIcon.pixel(i, j);
194       QColor aPixelColor(qRed(anRgb), qGreen(anRgb), qBlue(anRgb),
195                          qAlpha(aResult.pixel(i, j)));
196
197       QColor aLighterColor = aPixelColor.lighter(theLighterValue);
198       aResult.setPixel(i, j, qRgba(aLighterColor.red(), aLighterColor.green(),
199                                     aLighterColor.blue(), aLighterColor.alpha()));
200     }
201   }
202   return QPixmap::fromImage(aResult);
203 }
204
205 void setSpinText(ModuleBase_ParamSpinBox* theSpin, const QString& theText)
206 {
207   if (theSpin->text() == theText)
208     return;
209   // In order to avoid extra text setting because it will
210   // reset cursor position in control
211   bool isBlocked = theSpin->blockSignals(true);
212   theSpin->setText(theText);
213   theSpin->blockSignals(isBlocked);
214 }
215
216 void setSpinValue(QDoubleSpinBox* theSpin, double theValue)
217 {
218   if (fabs(theSpin->value() - theValue) < tolerance)
219     return;
220   bool isBlocked = theSpin->blockSignals(true);
221   theSpin->setValue(theValue);
222   theSpin->blockSignals(isBlocked);
223 }
224
225 void setSpinValue(ModuleBase_ParamSpinBox* theSpin, double theValue)
226 {
227   if (fabs(theSpin->value() - theValue) < tolerance)
228     return;
229   bool isBlocked = theSpin->blockSignals(true);
230   theSpin->setValue(theValue);
231   theSpin->blockSignals(isBlocked);
232 }
233
234 void setSpinText(ModuleBase_ParamIntSpinBox* theSpin, const QString& theText)
235 {
236   // In order to avoid extra text setting because it will
237   // reset cursor position in control
238   if (theSpin->text() == theText)
239     return;
240   bool isBlocked = theSpin->blockSignals(true);
241   theSpin->setText(theText);
242   theSpin->blockSignals(isBlocked);
243 }
244
245 void setSpinValue(ModuleBase_ParamIntSpinBox* theSpin, int theValue)
246 {
247   if (theSpin->value() == theValue)
248     return;
249   bool isBlocked = theSpin->blockSignals(true);
250   theSpin->setValue(theValue);
251   theSpin->blockSignals(isBlocked);
252 }
253
254 QAction* createAction(const QIcon& theIcon, const QString& theText,
255                       QObject* theParent, const QObject* theReceiver,
256                       const char* theMember, const QString& theToolTip,
257                       const QString& theStatusTip)
258 {
259   QAction* anAction = new QAction(theIcon, theText, theParent);
260   anAction->setToolTip(theToolTip.isEmpty() ? theText : theToolTip);
261   anAction->setStatusTip(!theStatusTip.isEmpty() ? theStatusTip :
262                                                    (!theToolTip.isEmpty() ? theToolTip : theText));
263   if (theReceiver)
264     QObject::connect(anAction, SIGNAL(triggered(bool)), theReceiver, theMember);
265
266   return anAction;
267 }
268
269 #ifdef _DEBUG
270 QString objectInfo(const ObjectPtr& theObj, const bool isUseAttributesInfo)
271 {
272   QString aFeatureStr = "feature";
273   if (!theObj.get())
274     return aFeatureStr;
275
276   std::ostringstream aPtrStr;
277   aPtrStr << "[" << theObj.get() << "]";
278
279   ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theObj);
280   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
281   if(aRes.get()) {
282     aFeatureStr.append(QString("(result%1)").arg(aPtrStr.str().c_str()).toStdString() .c_str());
283     if (aRes->isDisabled())
284       aFeatureStr.append("[disabled]");
285     if (aRes->isConcealed())
286       aFeatureStr.append("[concealed]");
287     if (ModelAPI_Tools::hasSubResults(aRes))
288       aFeatureStr.append("[hasSubResults]");
289
290     aFeature = ModelAPI_Feature::feature(aRes);
291   }
292   else
293     aFeatureStr.append(aPtrStr.str().c_str());
294
295   if (aFeature.get()) {
296     aFeatureStr.append(QString(": %1").arg(aFeature->getKind().c_str()).toStdString().c_str());
297     if (aFeature->data()->isValid()) {
298       aFeatureStr.append(QString(", name=%1").arg(theObj->data()->name().c_str()).toStdString()
299                                                                                        .c_str());
300     }
301     if (isUseAttributesInfo) {
302       std::set<std::shared_ptr<ModelAPI_Attribute> > anAttributes;
303       std::string aPointsInfo = ModelGeomAlgo_Point2D::getPontAttributesInfo(aFeature,
304                                                                           anAttributes).c_str();
305       if (!aPointsInfo.empty())
306         aFeatureStr.append(QString(", attributes: %1")
307           .arg(aPointsInfo.c_str()).toStdString().c_str());
308     }
309   }
310
311   return aFeatureStr;
312 }
313 #endif
314
315 typedef QMap<QString, int> ShapeTypes;
316 static ShapeTypes myShapeTypes;
317
318 int shapeType(const QString& theType)
319 {
320   if (myShapeTypes.count() == 0) {
321     myShapeTypes["compound"]   = TopAbs_COMPOUND;
322     myShapeTypes["compounds"]  = TopAbs_COMPOUND;
323     myShapeTypes["compsolid"]  = TopAbs_COMPSOLID;
324     myShapeTypes["compsolids"] = TopAbs_COMPSOLID;
325     myShapeTypes["solid"]      = TopAbs_SOLID;
326     myShapeTypes["solids"]     = TopAbs_SOLID;
327     myShapeTypes["shell"]      = TopAbs_SHELL;
328     myShapeTypes["shells"]     = TopAbs_SHELL;
329     myShapeTypes["face"]       = TopAbs_FACE;
330     myShapeTypes["faces"]      = TopAbs_FACE;
331     myShapeTypes["wire"]       = TopAbs_WIRE;
332     myShapeTypes["wires"]      = TopAbs_WIRE;
333     myShapeTypes["edge"]       = TopAbs_EDGE;
334     myShapeTypes["edges"]      = TopAbs_EDGE;
335     myShapeTypes["vertex"]     = TopAbs_VERTEX;
336     myShapeTypes["vertices"]   = TopAbs_VERTEX;
337     myShapeTypes["object"]     = ModuleBase_ResultPrs::Sel_Result;
338     myShapeTypes["objects"]    = ModuleBase_ResultPrs::Sel_Result;
339   }
340   QString aType = theType.toLower();
341   if(myShapeTypes.contains(aType))
342     return myShapeTypes[aType];
343   Events_InfoMessage("ModuleBase_Tools", "Shape type defined in XML is not implemented!").send();
344   return TopAbs_SHAPE;
345 }
346
347 void checkObjects(const QObjectPtrList& theObjects, bool& hasResult, bool& hasFeature,
348                   bool& hasParameter, bool& hasCompositeOwner)
349 {
350   hasResult = false;
351   hasFeature = false;
352   hasParameter = false;
353   hasCompositeOwner = false;
354   foreach(ObjectPtr aObj, theObjects) {
355     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
356     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
357     ResultParameterPtr aConstruction = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aResult);
358
359     hasResult |= (aResult.get() != NULL);
360     hasFeature |= (aFeature.get() != NULL);
361     hasParameter |= (aConstruction.get() != NULL);
362     if (hasFeature)
363       hasCompositeOwner |= (ModelAPI_Tools::compositeOwner(aFeature) != NULL);
364     if (hasFeature && hasResult  && hasParameter && hasCompositeOwner)
365       break;
366   }
367 }
368
369 /*bool setDefaultDeviationCoefficient(std::shared_ptr<GeomAPI_Shape> theGeomShape)
370 {
371   if (!theGeomShape.get())
372     return false;
373   // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
374   // correction of deviation for them should not influence to the application performance
375   GeomAPI_ShapeExplorer anExp(theGeomShape, GeomAPI_Shape::FACE);
376   bool anEmpty = anExp.empty();
377   return !anExp.more();
378 }*/
379
380 /*void setDefaultDeviationCoefficient(const std::shared_ptr<ModelAPI_Result>& theResult,
381                                     const Handle(Prs3d_Drawer)& theDrawer)
382 {
383   if (!theResult.get())
384     return;
385   bool aUseDeviation = false;
386
387   std::string aResultGroup = theResult->groupName();
388   if (aResultGroup == ModelAPI_ResultConstruction::group())
389     aUseDeviation = true;
390   else if (aResultGroup == ModelAPI_ResultBody::group()) {
391     GeomShapePtr aGeomShape = theResult->shape();
392     if (aGeomShape.get())
393       aUseDeviation = setDefaultDeviationCoefficient(aGeomShape);
394   }
395   if (aUseDeviation)
396     theDrawer->SetDeviationCoefficient(DEFAULT_DEVIATION_COEFFICIENT);
397 }
398 */
399 void setDefaultDeviationCoefficient(const TopoDS_Shape& theShape,
400                                     const Handle(Prs3d_Drawer)& theDrawer)
401 {
402   if (theShape.IsNull())
403     return;
404
405   std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape());
406   aGeomShape->setImpl(new TopoDS_Shape(theShape));
407
408   // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
409   // correction of deviation for them should not influence to the application performance
410   GeomAPI_ShapeExplorer anExp(aGeomShape, GeomAPI_Shape::FACE);
411   bool isConstruction = !anExp.more();
412
413   double aDeflection;
414   if (isConstruction)
415     aDeflection = Config_PropManager::real("Visualization", "construction_deflection",
416                                            ModelAPI_ResultConstruction::DEFAULT_DEFLECTION());
417   else
418     aDeflection = Config_PropManager::real("Visualization", "body_deflection",
419                                            ModelAPI_ResultBody::DEFAULT_DEFLECTION());
420
421   theDrawer->SetDeviationCoefficient(aDeflection);
422 }
423
424 Quantity_Color color(const std::string& theSection,
425                      const std::string& theName,
426                      const std::string& theDefault)
427 {
428   std::vector<int> aColor = Config_PropManager::color(theSection, theName, theDefault);
429   return Quantity_Color(aColor[0] / 255., aColor[1] / 255., aColor[2] / 255., Quantity_TOC_RGB);
430 }
431
432 ObjectPtr getObject(const AttributePtr& theAttribute)
433 {
434   ObjectPtr anObject;
435   std::string anAttrType = theAttribute->attributeType();
436   if (anAttrType == ModelAPI_AttributeRefAttr::typeId()) {
437     AttributeRefAttrPtr anAttr =
438       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
439     if (anAttr != NULL && anAttr->isObject())
440       anObject = anAttr->object();
441   }
442   if (anAttrType == ModelAPI_AttributeSelection::typeId()) {
443     AttributeSelectionPtr anAttr =
444       std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
445     if (anAttr != NULL)
446       anObject = anAttr->context();
447   }
448   if (anAttrType == ModelAPI_AttributeReference::typeId()) {
449     AttributeReferencePtr anAttr =
450       std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
451     if (anAttr.get() != NULL)
452       anObject = anAttr->value();
453   }
454   return anObject;
455 }
456
457 TopAbs_ShapeEnum getCompoundSubType(const TopoDS_Shape& theShape)
458 {
459   TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
460
461   // for compounds check sub-shapes: it may be compound of needed type:
462   // Booleans may produce compounds of Solids
463   if (aShapeType == TopAbs_COMPOUND) {
464     for(TopoDS_Iterator aSubs(theShape); aSubs.More(); aSubs.Next()) {
465       if (!aSubs.Value().IsNull()) {
466         TopAbs_ShapeEnum aSubType = aSubs.Value().ShapeType();
467         if (aSubType == TopAbs_COMPOUND) { // compound of compound(s)
468           aShapeType = TopAbs_COMPOUND;
469           break;
470         }
471         if (aShapeType == TopAbs_COMPOUND) {
472           aShapeType = aSubType;
473         } else if (aShapeType != aSubType) { // compound of shapes of different types
474           aShapeType = TopAbs_COMPOUND;
475           break;
476         }
477       }
478     }
479   }
480   return aShapeType;
481 }
482
483 void getParameters(QStringList& theParameters)
484 {
485   theParameters.clear();
486
487   SessionPtr aSession = ModelAPI_Session::get();
488   std::list<DocumentPtr> aDocList;
489   DocumentPtr anActiveDocument = aSession->activeDocument();
490   DocumentPtr aRootDocument = aSession->moduleDocument();
491   aDocList.push_back(anActiveDocument);
492   if (anActiveDocument != aRootDocument) {
493     aDocList.push_back(aRootDocument);
494   }
495   std::string aGroupId = ModelAPI_ResultParameter::group();
496   for(std::list<DocumentPtr>::const_iterator it = aDocList.begin(); it != aDocList.end(); ++it) {
497     DocumentPtr aDocument = *it;
498     int aSize = aDocument->size(aGroupId);
499     for (int i = 0; i < aSize; i++) {
500       ObjectPtr anObject = aDocument->object(aGroupId, i);
501       std::string aParameterName = anObject->data()->name();
502       theParameters.append(aParameterName.c_str());
503     }
504   }
505 }
506
507 std::string findGreedAttribute(ModuleBase_IWorkshop* theWorkshop,
508                                const FeaturePtr& theFeature)
509 {
510   std::string anAttributeId;
511
512   std::string aXmlCfg, aDescription;
513   theWorkshop->module()->getXMLRepresentation(theFeature->getKind(), aXmlCfg, aDescription);
514
515   ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
516   std::string anAttributeTitle;
517   aFactory.getGreedAttribute(anAttributeId);
518
519   return anAttributeId;
520 }
521
522 bool hasObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
523                const std::shared_ptr<GeomAPI_Shape>& theShape,
524                ModuleBase_IWorkshop* theWorkshop,
525                const bool theTemporarily)
526 {
527   bool aHasObject = false;
528   if (!theAttribute.get())
529     return aHasObject;
530
531   std::string aType = theAttribute->attributeType();
532   if (aType == ModelAPI_AttributeReference::typeId()) {
533     AttributeReferencePtr aRef =
534       std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
535     ObjectPtr aObject = aRef->value();
536     aHasObject = aObject && aObject->isSame(theObject);
537     //if (!(aObject && aObject->isSame(theObject))) {
538     //  aRef->setValue(theObject);
539     //}
540   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
541     AttributeRefAttrPtr aRefAttr =
542       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
543
544     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
545     if (anAttribute.get()) {
546       //aRefAttr->setAttr(anAttribute);
547     }
548     else {
549       ObjectPtr aObject = aRefAttr->object();
550       aHasObject = aObject && aObject->isSame(theObject);
551       //if (!(aObject && aObject->isSame(theObject))) {
552       //  aRefAttr->setObject(theObject);
553       //}
554     }
555   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
556     /*AttributeSelectionPtr aSelectAttr =
557                              std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
558     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
559     if (aSelectAttr.get() != NULL) {
560       aSelectAttr->setValue(aResult, theShape, theTemporarily);
561     }*/
562   }
563   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
564     AttributeSelectionListPtr aSelectionListAttr =
565                          std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
566     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
567     aHasObject = aSelectionListAttr->isInList(aResult, theShape, theTemporarily);
568   }
569   else if (aType == ModelAPI_AttributeRefList::typeId()) {
570     AttributeRefListPtr aRefListAttr =
571       std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
572     aHasObject = aRefListAttr->isInList(theObject);
573     //if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
574     //  aRefListAttr->append(theObject);
575   }
576   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
577     AttributeRefAttrListPtr aRefAttrListAttr =
578       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
579     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
580
581     if (anAttribute.get()) {
582       aHasObject = aRefAttrListAttr->isInList(anAttribute);
583       //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
584       //  aRefAttrListAttr->append(anAttribute);
585     }
586     else {
587       aHasObject = aRefAttrListAttr->isInList(theObject);
588       //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
589       //  aRefAttrListAttr->append(theObject);
590     }
591   }
592   return aHasObject;
593 }
594
595 bool setObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
596                const GeomShapePtr& theShape, ModuleBase_IWorkshop* theWorkshop,
597                const bool theTemporarily, const bool theCheckIfAttributeHasObject)
598 {
599   if (!theAttribute.get())
600     return false;
601
602   bool isDone = true;
603   std::string aType = theAttribute->attributeType();
604   if (aType == ModelAPI_AttributeReference::typeId()) {
605     AttributeReferencePtr aRef =
606       std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
607     ObjectPtr aObject = aRef->value();
608     if (!(aObject && aObject->isSame(theObject))) {
609       aRef->setValue(theObject);
610     }
611   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
612     AttributeRefAttrPtr aRefAttr =
613       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
614
615     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
616     if (anAttribute.get())
617       aRefAttr->setAttr(anAttribute);
618     else {
619       ObjectPtr aObject = aRefAttr->object();
620       if (!(aObject && aObject->isSame(theObject))) {
621         aRefAttr->setObject(theObject);
622       }
623     }
624   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
625     AttributeSelectionPtr aSelectAttr =
626                              std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
627     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
628     if (aSelectAttr.get() != NULL) {
629       aSelectAttr->setValue(aResult, theShape, theTemporarily);
630     }
631   }
632   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
633     AttributeSelectionListPtr aSelectionListAttr =
634                          std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
635     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
636     if (!theCheckIfAttributeHasObject ||
637         !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
638       aSelectionListAttr->append(aResult, theShape, theTemporarily);
639   }
640   else if (aType == ModelAPI_AttributeRefList::typeId()) {
641     AttributeRefListPtr aRefListAttr =
642       std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
643     if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject)) {
644       if (theObject.get())
645         aRefListAttr->append(theObject);
646       else
647         isDone = false;
648     }
649   }
650   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
651     AttributeRefAttrListPtr aRefAttrListAttr =
652       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
653     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
654
655     if (anAttribute.get()) {
656       if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
657         aRefAttrListAttr->append(anAttribute);
658     }
659     else {
660       if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject)) {
661         if (theObject.get())
662           aRefAttrListAttr->append(theObject);
663         else
664           isDone = false;
665       }
666     }
667   }
668   return isDone;
669 }
670
671 GeomShapePtr getShape(const AttributePtr& theAttribute, ModuleBase_IWorkshop* theWorkshop)
672 {
673   GeomShapePtr aShape;
674   if (!theAttribute.get())
675     return aShape;
676
677   std::string aType = theAttribute->attributeType();
678   if (aType == ModelAPI_AttributeReference::typeId()) {
679   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
680     AttributeRefAttrPtr aRefAttr =
681       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
682     if (aRefAttr.get() && !aRefAttr->isObject()) {
683       AttributePtr anAttribute = aRefAttr->attr();
684       aShape = theWorkshop->module()->findShape(anAttribute);
685     }
686   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
687     AttributeSelectionPtr aSelectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>
688                                                                                  (theAttribute);
689     aShape = aSelectAttr->value();
690   }
691   else // Geom2D point processing
692     aShape = theWorkshop->module()->findShape(theAttribute);
693   return aShape;
694 }
695
696 void flushUpdated(ObjectPtr theObject)
697 {
698   blockUpdateViewer(true);
699
700   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
701
702   blockUpdateViewer(false);
703 }
704
705 void blockUpdateViewer(const bool theValue)
706 {
707   // the viewer update should be blocked in order to avoid the temporary feature content
708   // when the solver processes the feature, the redisplay message can be flushed
709   // what caused the display in the viewer preliminary states of object
710   // e.g. fillet feature, angle value change
711   std::shared_ptr<Events_Message> aMsg;
712   if (theValue) {
713     aMsg = std::shared_ptr<Events_Message>(
714         new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)));
715   }
716   else {
717     // the viewer update should be unblocked
718     aMsg = std::shared_ptr<Events_Message>(
719         new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)));
720   }
721   Events_Loop::loop()->send(aMsg);
722 }
723
724 QString wrapTextByWords(const QString& theValue, QWidget* theWidget,
725                                           int theMaxLineInPixels)
726 {
727   static QFontMetrics tfm(theWidget ? theWidget->font() : QApplication::font());
728   static qreal phi = 2.618;
729
730   QRect aBounds = tfm.boundingRect(theValue);
731   if(aBounds.width() <= theMaxLineInPixels)
732     return theValue;
733
734   qreal s = aBounds.width() * aBounds.height();
735   qreal aGoldWidth = sqrt(s*phi);
736
737   QStringList aWords = theValue.split(" ", QString::SkipEmptyParts);
738   QStringList aLines;
739   int n = aWords.count();
740   QString aLine;
741   for (int i = 0; i < n; i++) {
742     QString aLineExt = aLine + " " + aWords[i];
743     qreal anWidthNonExt = tfm.boundingRect(aLine).width();
744     qreal anWidthExt = tfm.boundingRect(aLineExt).width();
745     qreal aDeltaNonExt = fabs(anWidthNonExt-aGoldWidth);
746     qreal aDeltaExt    = fabs(anWidthExt-aGoldWidth);
747     if(aDeltaNonExt < aDeltaExt) {
748       // new line
749       aLines.append(aLine);
750       aLine = aWords[i];
751     }
752     else
753       aLine = aLineExt;
754   }
755
756   if(!aLine.isEmpty())
757     aLines.append(aLine);
758
759   QString aResult = aLines.join("\n");
760   return aResult;
761 }
762
763 //**************************************************************
764 QLocale doubleLocale()
765 {
766   // VSR 01/07/2010: Disable thousands separator for spin box
767   // (to avoid inconsistency of double-2-string and string-2-double conversion)
768   QLocale aLocale;
769   aLocale.setNumberOptions(aLocale.numberOptions() |
770                            QLocale::OmitGroupSeparator |
771                            QLocale::RejectGroupSeparator);
772   return aLocale;
773 }
774
775 //**************************************************************
776 void refsToFeatureInFeatureDocument(const ObjectPtr& theObject,
777                                     std::set<FeaturePtr>& theRefFeatures)
778 {
779   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
780   if (aFeature.get()) {
781     DocumentPtr aFeatureDoc = aFeature->document();
782     // 1. find references in the current document
783     aFeatureDoc->refsToFeature(aFeature, theRefFeatures, false);
784   }
785 }
786
787
788 //**************************************************************
789 /*bool isSubOfComposite(const ObjectPtr& theObject)
790 {
791   bool isSub = false;
792   std::set<FeaturePtr> aRefFeatures;
793   refsToFeatureInFeatureDocument(theObject, aRefFeatures);
794   std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
795                                        aLast = aRefFeatures.end();
796   for (; anIt != aLast && !isSub; anIt++) {
797     isSub = isSubOfComposite(theObject, *anIt);
798   }
799   return isSub;
800 }*/
801
802 //**************************************************************
803 /*bool isSubOfComposite(const ObjectPtr& theObject, const FeaturePtr& theFeature)
804 {
805   bool isSub = false;
806   CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
807   if (aComposite.get()) {
808     isSub = aComposite->isSub(theObject);
809     // the recursive is possible, the parameters are sketch circle and extrusion cut. They are
810     // separated by composite sketch feature
811     if (!isSub) {
812       int aNbSubs = aComposite->numberOfSubs();
813       for (int aSub = 0; aSub < aNbSubs && !isSub; aSub++) {
814         isSub = isSubOfComposite(theObject, aComposite->subFeature(aSub));
815       }
816     }
817   }
818   return isSub;
819 }*/
820
821 //**************************************************************
822 ResultPtr firstResult(const ObjectPtr& theObject)
823 {
824   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
825   if (!aResult.get()) {
826     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
827     if (aFeature.get())
828       aResult = aFeature->firstResult();
829   }
830   return aResult;
831 }
832
833 //**************************************************************
834 bool isFeatureOfResult(const FeaturePtr& theFeature, const std::string& theGroupOfResult)
835 {
836   bool isResult = false;
837
838   if (!theFeature->data()->isValid())
839     return isResult;
840
841   ResultPtr aFirstResult = theFeature->firstResult();
842   if (!aFirstResult.get())
843     return isResult;
844
845   return aFirstResult->groupName() == theGroupOfResult;
846 }
847
848 //**************************************************************
849 bool hasModuleDocumentFeature(const std::set<FeaturePtr>& theFeatures)
850 {
851   bool aFoundModuleDocumentObject = false;
852   DocumentPtr aModuleDoc = ModelAPI_Session::get()->moduleDocument();
853
854   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(), aLast = theFeatures.end();
855   for (; anIt != aLast && !aFoundModuleDocumentObject; anIt++) {
856     FeaturePtr aFeature = *anIt;
857     ResultPtr aResult = ModuleBase_Tools::firstResult(aFeature);
858     if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group())
859       continue;
860     aFoundModuleDocumentObject = aFeature->document() == aModuleDoc;
861   }
862
863   return aFoundModuleDocumentObject;
864 }
865
866 //**************************************************************
867 bool askToDelete(const std::set<FeaturePtr> theFeatures,
868                  const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
869                  QWidget* theParent,
870                  std::set<FeaturePtr>& theReferencesToDelete,
871                  const std::string& thePrefixInfo)
872 {
873   QString aNotActivatedDocWrn;
874   std::string aNotActivatedNames;
875   if (!ModelAPI_Tools::allDocumentsActivated(aNotActivatedNames)) {
876     if (ModuleBase_Tools::hasModuleDocumentFeature(theFeatures))
877       aNotActivatedDocWrn =
878         QObject::tr("Selected objects can be used in Part documents which are not loaded:%1.\n")
879                             .arg(aNotActivatedNames.c_str());
880   }
881
882   std::set<FeaturePtr> aFeaturesRefsTo;
883   std::set<FeaturePtr> aFeaturesRefsToParameter;
884   std::set<FeaturePtr> aParameterFeatures;
885   QStringList aPartFeatureNames;
886   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
887                                        aLast = theFeatures.end();
888   // separate features to references to parameter features and references to others
889   for (; anIt != aLast; anIt++) {
890     FeaturePtr aFeature = *anIt;
891     if (theReferences.find(aFeature) == theReferences.end())
892       continue;
893
894     if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
895       aPartFeatureNames.append(aFeature->name().c_str());
896
897     std::set<FeaturePtr> aRefFeatures;
898     std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
899     std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
900     for (; aRefIt != aRefLast; aRefIt++) {
901       FeaturePtr aRefFeature = *aRefIt;
902       if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
903           aRefFeatures.find(aRefFeature) == aRefFeatures.end()) // it is not added
904         aRefFeatures.insert(aRefFeature);
905     }
906
907     if (isFeatureOfResult(aFeature, ModelAPI_ResultParameter::group())) {
908       aFeaturesRefsToParameter.insert(aRefFeatures.begin(), aRefFeatures.end());
909       aParameterFeatures.insert(aFeature);
910     }
911     else {
912       theReferencesToDelete.insert(aRefFeatures.begin(), aRefFeatures.end());
913     }
914   }
915
916   std::set<FeaturePtr> aFeaturesRefsToParameterOnly;
917   anIt = aFeaturesRefsToParameter.begin();
918   aLast = aFeaturesRefsToParameter.end();
919   // separate features to references to parameter features and references to others
920   QStringList aParamFeatureNames;
921   for (; anIt != aLast; anIt++) {
922     FeaturePtr aFeature = *anIt;
923     if (theReferencesToDelete.find(aFeature) == theReferencesToDelete.end()) {
924       aFeaturesRefsToParameterOnly.insert(aFeature);
925       aParamFeatureNames.append(aFeature->name().c_str());
926     }
927   }
928   aParamFeatureNames.sort();
929   QStringList anOtherFeatureNames;
930   anIt = theReferencesToDelete.begin();
931   aLast = theReferencesToDelete.end();
932   for (; anIt != aLast; anIt++) {
933     FeaturePtr aFeature = *anIt;
934     if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
935       aPartFeatureNames.append(aFeature->name().c_str());
936     else
937       anOtherFeatureNames.append(aFeature->name().c_str());
938   }
939   aPartFeatureNames.sort();
940   anOtherFeatureNames.sort();
941
942   bool aCanReplaceParameters = !aFeaturesRefsToParameterOnly.empty();
943
944   QMessageBox aMessageBox(theParent);
945   aMessageBox.setWindowTitle(QObject::tr("Delete features"));
946   aMessageBox.setIcon(QMessageBox::Warning);
947   aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
948   aMessageBox.setDefaultButton(QMessageBox::No);
949
950   QString aText;
951   if (!thePrefixInfo.empty())
952     aText = thePrefixInfo.c_str();
953   QString aSep = ", ";
954   if (!aPartFeatureNames.empty()) {
955     aText += QString(QObject::tr("The following parts will be deleted: %1.\n"))
956              .arg(aPartFeatureNames.join(aSep));
957   }
958   if (!aNotActivatedDocWrn.isEmpty())
959     aText += aNotActivatedDocWrn;
960   if (!anOtherFeatureNames.empty()) {
961     const char* aMsg = "Features are used in the following features: %1.\nThese "
962                        "features will be deleted.\n";
963     aText += QString(QObject::tr(aMsg))
964                      .arg(anOtherFeatureNames.join(aSep));
965   }
966   if (!aParamFeatureNames.empty()) {
967     const char* aMsg = "Parameters are used in the following features: %1.\nThese features will "
968                        "be deleted.\nOr parameters could be replaced by their values.\n";
969     aText += QString(QObject::tr(aMsg))
970                      .arg(aParamFeatureNames.join(aSep));
971     QPushButton *aReplaceButton =
972       aMessageBox.addButton(QObject::tr("Replace"), QMessageBox::ActionRole);
973   }
974
975   if (!aText.isEmpty()) {
976     aText += "Would you like to continue?";
977     aMessageBox.setText(aText);
978     aMessageBox.exec();
979     QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
980
981     if (aButtonRole == QMessageBox::NoRole)
982       return false;
983
984     if (aButtonRole == QMessageBox::ActionRole) {
985       foreach (FeaturePtr aObj, aParameterFeatures)
986         ModelAPI_ReplaceParameterMessage::send(aObj, 0);
987     }
988     else
989       theReferencesToDelete.insert(aFeaturesRefsToParameterOnly.begin(),
990                                    aFeaturesRefsToParameterOnly.end());
991   }
992   return true;
993 }
994
995 //**************************************************************
996 void convertToFeatures(const QObjectPtrList& theObjects, std::set<FeaturePtr>& theFeatures)
997 {
998   QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
999   for(; anIt != aLast; anIt++) {
1000     ObjectPtr anObject = *anIt;
1001     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1002     // for parameter result, use the corresponded reature to be removed
1003     if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1004       aFeature = ModelAPI_Feature::feature(anObject);
1005     }
1006     theFeatures.insert(aFeature);
1007   }
1008 }
1009
1010 QString translate(const Events_InfoMessage& theMessage)
1011 {
1012   QString aMessage;
1013
1014   if (!theMessage.empty()) {
1015     std::string aStr = Config_Translator::translate(theMessage);
1016     if (!aStr.empty()) {
1017       std::string aCodec = Config_Translator::codec(theMessage);
1018       aMessage = QTextCodec::codecForName(aCodec.c_str())->toUnicode(aStr.c_str());
1019     }
1020   }
1021
1022   return aMessage;
1023 }
1024
1025 QString translate(const std::string& theContext, const std::string& theMessage)
1026 {
1027   QString aMessage;
1028
1029   if (!theMessage.empty()) {
1030     std::string aStr = Config_Translator::translate(theContext, theMessage);
1031     if (!aStr.empty()) {
1032       std::string aCodec = Config_Translator::codec(theContext);
1033       aMessage = QTextCodec::codecForName(aCodec.c_str())->toUnicode(aStr.c_str());
1034     }
1035   }
1036
1037   return aMessage;
1038 }
1039
1040 void setPointBallHighlighting(AIS_Shape* theAIS)
1041 {
1042   static Handle(Image_AlienPixMap) aPixMap;
1043   if(aPixMap.IsNull()) {
1044     // Load icon for the presentation
1045     std::string aFile;
1046     char* anEnv = getenv("SHAPER_ROOT_DIR");
1047     if(anEnv) {
1048       aFile = std::string(anEnv) +
1049         FSEP + "share" + FSEP + "salome" + FSEP + "resources" + FSEP + "shaper";
1050     } else {
1051       anEnv = getenv("OPENPARTS_ROOT_DIR");
1052       if (anEnv)
1053         aFile = std::string(anEnv) + FSEP + "resources";
1054     }
1055
1056     aFile += FSEP;
1057     static const std::string aMarkerName = "marker_dot.png";
1058     aFile += aMarkerName;
1059     aPixMap = new Image_AlienPixMap();
1060     if(!aPixMap->Load(aFile.c_str())) {
1061       // The icon for constraint is not found
1062       static const std::string aMsg =
1063         "Error: Point market not found by path: \"" + aFile + "\". Falling back.";
1064       //Events_InfoMessage("ModuleBase_Tools::setPointBallHighlighting", aMsg).send();
1065     }
1066   }
1067
1068   Handle(Graphic3d_AspectMarker3d) anAspect;
1069   Handle(Prs3d_Drawer) aDrawer = theAIS->HilightAttributes();
1070   if(aDrawer->HasOwnPointAspect()) {
1071     Handle(Prs3d_PointAspect) aPntAspect = aDrawer->PointAspect();
1072     if(aPixMap->IsEmpty()) {
1073       anAspect = aPntAspect->Aspect();
1074       anAspect->SetType(Aspect_TOM_BALL);
1075     } else {
1076       if(aPixMap->Format() == Image_PixMap::ImgGray) {
1077         aPixMap->SetFormat (Image_PixMap::ImgAlpha);
1078       } else if(aPixMap->Format() == Image_PixMap::ImgGrayF) {
1079         aPixMap->SetFormat (Image_PixMap::ImgAlphaF);
1080       }
1081       anAspect = new Graphic3d_AspectMarker3d(aPixMap);
1082       aPntAspect->SetAspect(anAspect);
1083     }
1084     aDrawer->SetPointAspect(aPntAspect);
1085     theAIS->SetHilightAttributes(aDrawer);
1086   }
1087 }
1088
1089 } // namespace ModuleBase_Tools
1090
1091