Salome HOME
0114238db64c52e8c18e35f2d88954a3a2bb71e3
[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 QString objectInfo(const ObjectPtr& theObj, const bool isUseAttributesInfo)
270 {
271   QString aFeatureStr = "feature";
272   if (!theObj.get())
273     return aFeatureStr;
274
275   std::ostringstream aPtrStr;
276   aPtrStr << "[" << theObj.get() << "]";
277
278   ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theObj);
279   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
280   if(aRes.get()) {
281     aFeatureStr.append(QString("(result%1)").arg(aPtrStr.str().c_str()).toStdString() .c_str());
282     if (aRes->isDisabled())
283       aFeatureStr.append("[disabled]");
284     if (aRes->isConcealed())
285       aFeatureStr.append("[concealed]");
286     if (ModelAPI_Tools::hasSubResults(aRes))
287       aFeatureStr.append("[hasSubResults]");
288
289     aFeature = ModelAPI_Feature::feature(aRes);
290   }
291   else
292     aFeatureStr.append(aPtrStr.str().c_str());
293
294   if (aFeature.get()) {
295     aFeatureStr.append(QString(": %1").arg(aFeature->getKind().c_str()).toStdString().c_str());
296     if (aFeature->data()->isValid()) {
297       aFeatureStr.append(QString(", name=%1").arg(theObj->data()->name().c_str()).toStdString()
298                                                                                        .c_str());
299     }
300     if (isUseAttributesInfo) {
301       std::set<std::shared_ptr<ModelAPI_Attribute> > anAttributes;
302       std::string aPointsInfo = ModelGeomAlgo_Point2D::getPontAttributesInfo(aFeature,
303                                                                           anAttributes).c_str();
304       if (!aPointsInfo.empty())
305         aFeatureStr.append(QString(", attributes: %1")
306           .arg(aPointsInfo.c_str()).toStdString().c_str());
307     }
308   }
309
310   return aFeatureStr;
311 }
312
313 typedef QMap<QString, int> ShapeTypes;
314 static ShapeTypes myShapeTypes;
315
316 int shapeType(const QString& theType)
317 {
318   if (myShapeTypes.count() == 0) {
319     myShapeTypes["compound"]   = TopAbs_COMPOUND;
320     myShapeTypes["compounds"]  = TopAbs_COMPOUND;
321     myShapeTypes["compsolid"]  = TopAbs_COMPSOLID;
322     myShapeTypes["compsolids"] = TopAbs_COMPSOLID;
323     myShapeTypes["solid"]      = TopAbs_SOLID;
324     myShapeTypes["solids"]     = TopAbs_SOLID;
325     myShapeTypes["shell"]      = TopAbs_SHELL;
326     myShapeTypes["shells"]     = TopAbs_SHELL;
327     myShapeTypes["face"]       = TopAbs_FACE;
328     myShapeTypes["faces"]      = TopAbs_FACE;
329     myShapeTypes["wire"]       = TopAbs_WIRE;
330     myShapeTypes["wires"]      = TopAbs_WIRE;
331     myShapeTypes["edge"]       = TopAbs_EDGE;
332     myShapeTypes["edges"]      = TopAbs_EDGE;
333     myShapeTypes["vertex"]     = TopAbs_VERTEX;
334     myShapeTypes["vertices"]   = TopAbs_VERTEX;
335     myShapeTypes["object"]     = ModuleBase_ResultPrs::Sel_Result;
336     myShapeTypes["objects"]    = ModuleBase_ResultPrs::Sel_Result;
337   }
338   QString aType = theType.toLower();
339   if(myShapeTypes.contains(aType))
340     return myShapeTypes[aType];
341   Events_InfoMessage("ModuleBase_Tools", "Shape type defined in XML is not implemented!").send();
342   return TopAbs_SHAPE;
343 }
344
345 void checkObjects(const QObjectPtrList& theObjects, bool& hasResult, bool& hasFeature,
346                   bool& hasParameter, bool& hasCompositeOwner)
347 {
348   hasResult = false;
349   hasFeature = false;
350   hasParameter = false;
351   hasCompositeOwner = false;
352   foreach(ObjectPtr aObj, theObjects) {
353     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
354     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
355     ResultParameterPtr aConstruction = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aResult);
356
357     hasResult |= (aResult.get() != NULL);
358     hasFeature |= (aFeature.get() != NULL);
359     hasParameter |= (aConstruction.get() != NULL);
360     if (hasFeature)
361       hasCompositeOwner |= (ModelAPI_Tools::compositeOwner(aFeature) != NULL);
362     if (hasFeature && hasResult  && hasParameter && hasCompositeOwner)
363       break;
364   }
365 }
366
367 /*bool setDefaultDeviationCoefficient(std::shared_ptr<GeomAPI_Shape> theGeomShape)
368 {
369   if (!theGeomShape.get())
370     return false;
371   // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
372   // correction of deviation for them should not influence to the application performance
373   GeomAPI_ShapeExplorer anExp(theGeomShape, GeomAPI_Shape::FACE);
374   bool anEmpty = anExp.empty();
375   return !anExp.more();
376 }*/
377
378 /*void setDefaultDeviationCoefficient(const std::shared_ptr<ModelAPI_Result>& theResult,
379                                     const Handle(Prs3d_Drawer)& theDrawer)
380 {
381   if (!theResult.get())
382     return;
383   bool aUseDeviation = false;
384
385   std::string aResultGroup = theResult->groupName();
386   if (aResultGroup == ModelAPI_ResultConstruction::group())
387     aUseDeviation = true;
388   else if (aResultGroup == ModelAPI_ResultBody::group()) {
389     GeomShapePtr aGeomShape = theResult->shape();
390     if (aGeomShape.get())
391       aUseDeviation = setDefaultDeviationCoefficient(aGeomShape);
392   }
393   if (aUseDeviation)
394     theDrawer->SetDeviationCoefficient(DEFAULT_DEVIATION_COEFFICIENT);
395 }
396 */
397 void setDefaultDeviationCoefficient(const TopoDS_Shape& theShape,
398                                     const Handle(Prs3d_Drawer)& theDrawer)
399 {
400   if (theShape.IsNull())
401     return;
402
403   std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape());
404   aGeomShape->setImpl(new TopoDS_Shape(theShape));
405
406   // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
407   // correction of deviation for them should not influence to the application performance
408   GeomAPI_ShapeExplorer anExp(aGeomShape, GeomAPI_Shape::FACE);
409   bool isConstruction = !anExp.more();
410
411   double aDeflection;
412   if (isConstruction)
413     aDeflection = Config_PropManager::real("Visualization", "construction_deflection",
414                                            ModelAPI_ResultConstruction::DEFAULT_DEFLECTION());
415   else
416     aDeflection = Config_PropManager::real("Visualization", "body_deflection",
417                                            ModelAPI_ResultBody::DEFAULT_DEFLECTION());
418
419   theDrawer->SetDeviationCoefficient(aDeflection);
420 }
421
422 Quantity_Color color(const std::string& theSection,
423                      const std::string& theName,
424                      const std::string& theDefault)
425 {
426   std::vector<int> aColor = Config_PropManager::color(theSection, theName, theDefault);
427   return Quantity_Color(aColor[0] / 255., aColor[1] / 255., aColor[2] / 255., Quantity_TOC_RGB);
428 }
429
430 ObjectPtr getObject(const AttributePtr& theAttribute)
431 {
432   ObjectPtr anObject;
433   std::string anAttrType = theAttribute->attributeType();
434   if (anAttrType == ModelAPI_AttributeRefAttr::typeId()) {
435     AttributeRefAttrPtr anAttr =
436       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
437     if (anAttr != NULL && anAttr->isObject())
438       anObject = anAttr->object();
439   }
440   if (anAttrType == ModelAPI_AttributeSelection::typeId()) {
441     AttributeSelectionPtr anAttr =
442       std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
443     if (anAttr != NULL)
444       anObject = anAttr->context();
445   }
446   if (anAttrType == ModelAPI_AttributeReference::typeId()) {
447     AttributeReferencePtr anAttr =
448       std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
449     if (anAttr.get() != NULL)
450       anObject = anAttr->value();
451   }
452   return anObject;
453 }
454
455 TopAbs_ShapeEnum getCompoundSubType(const TopoDS_Shape& theShape)
456 {
457   TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
458
459   // for compounds check sub-shapes: it may be compound of needed type:
460   // Booleans may produce compounds of Solids
461   if (aShapeType == TopAbs_COMPOUND) {
462     for(TopoDS_Iterator aSubs(theShape); aSubs.More(); aSubs.Next()) {
463       if (!aSubs.Value().IsNull()) {
464         TopAbs_ShapeEnum aSubType = aSubs.Value().ShapeType();
465         if (aSubType == TopAbs_COMPOUND) { // compound of compound(s)
466           aShapeType = TopAbs_COMPOUND;
467           break;
468         }
469         if (aShapeType == TopAbs_COMPOUND) {
470           aShapeType = aSubType;
471         } else if (aShapeType != aSubType) { // compound of shapes of different types
472           aShapeType = TopAbs_COMPOUND;
473           break;
474         }
475       }
476     }
477   }
478   return aShapeType;
479 }
480
481 void getParameters(QStringList& theParameters)
482 {
483   theParameters.clear();
484
485   SessionPtr aSession = ModelAPI_Session::get();
486   std::list<DocumentPtr> aDocList;
487   DocumentPtr anActiveDocument = aSession->activeDocument();
488   DocumentPtr aRootDocument = aSession->moduleDocument();
489   aDocList.push_back(anActiveDocument);
490   if (anActiveDocument != aRootDocument) {
491     aDocList.push_back(aRootDocument);
492   }
493   std::string aGroupId = ModelAPI_ResultParameter::group();
494   for(std::list<DocumentPtr>::const_iterator it = aDocList.begin(); it != aDocList.end(); ++it) {
495     DocumentPtr aDocument = *it;
496     int aSize = aDocument->size(aGroupId);
497     for (int i = 0; i < aSize; i++) {
498       ObjectPtr anObject = aDocument->object(aGroupId, i);
499       std::string aParameterName = anObject->data()->name();
500       theParameters.append(aParameterName.c_str());
501     }
502   }
503 }
504
505 std::string findGreedAttribute(ModuleBase_IWorkshop* theWorkshop,
506                                const FeaturePtr& theFeature)
507 {
508   std::string anAttributeId;
509
510   std::string aXmlCfg, aDescription;
511   theWorkshop->module()->getXMLRepresentation(theFeature->getKind(), aXmlCfg, aDescription);
512
513   ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
514   std::string anAttributeTitle;
515   aFactory.getGreedAttribute(anAttributeId);
516
517   return anAttributeId;
518 }
519
520 bool hasObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
521                const std::shared_ptr<GeomAPI_Shape>& theShape,
522                ModuleBase_IWorkshop* theWorkshop,
523                const bool theTemporarily)
524 {
525   bool aHasObject = false;
526   if (!theAttribute.get())
527     return aHasObject;
528
529   std::string aType = theAttribute->attributeType();
530   if (aType == ModelAPI_AttributeReference::typeId()) {
531     AttributeReferencePtr aRef =
532       std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
533     ObjectPtr aObject = aRef->value();
534     aHasObject = aObject && aObject->isSame(theObject);
535     //if (!(aObject && aObject->isSame(theObject))) {
536     //  aRef->setValue(theObject);
537     //}
538   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
539     AttributeRefAttrPtr aRefAttr =
540       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
541
542     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
543     if (anAttribute.get()) {
544       //aRefAttr->setAttr(anAttribute);
545     }
546     else {
547       ObjectPtr aObject = aRefAttr->object();
548       aHasObject = aObject && aObject->isSame(theObject);
549       //if (!(aObject && aObject->isSame(theObject))) {
550       //  aRefAttr->setObject(theObject);
551       //}
552     }
553   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
554     /*AttributeSelectionPtr aSelectAttr =
555                              std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
556     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
557     if (aSelectAttr.get() != NULL) {
558       aSelectAttr->setValue(aResult, theShape, theTemporarily);
559     }*/
560   }
561   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
562     AttributeSelectionListPtr aSelectionListAttr =
563                          std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
564     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
565     aHasObject = aSelectionListAttr->isInList(aResult, theShape, theTemporarily);
566   }
567   else if (aType == ModelAPI_AttributeRefList::typeId()) {
568     AttributeRefListPtr aRefListAttr =
569       std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
570     aHasObject = aRefListAttr->isInList(theObject);
571     //if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
572     //  aRefListAttr->append(theObject);
573   }
574   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
575     AttributeRefAttrListPtr aRefAttrListAttr =
576       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
577     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
578
579     if (anAttribute.get()) {
580       aHasObject = aRefAttrListAttr->isInList(anAttribute);
581       //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
582       //  aRefAttrListAttr->append(anAttribute);
583     }
584     else {
585       aHasObject = aRefAttrListAttr->isInList(theObject);
586       //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
587       //  aRefAttrListAttr->append(theObject);
588     }
589   }
590   return aHasObject;
591 }
592
593 bool setObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
594                const GeomShapePtr& theShape, ModuleBase_IWorkshop* theWorkshop,
595                const bool theTemporarily, const bool theCheckIfAttributeHasObject)
596 {
597   if (!theAttribute.get())
598     return false;
599
600   bool isDone = true;
601   std::string aType = theAttribute->attributeType();
602   if (aType == ModelAPI_AttributeReference::typeId()) {
603     AttributeReferencePtr aRef =
604       std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
605     ObjectPtr aObject = aRef->value();
606     if (!(aObject && aObject->isSame(theObject))) {
607       aRef->setValue(theObject);
608     }
609   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
610     AttributeRefAttrPtr aRefAttr =
611       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
612
613     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
614     if (anAttribute.get())
615       aRefAttr->setAttr(anAttribute);
616     else {
617       ObjectPtr aObject = aRefAttr->object();
618       if (!(aObject && aObject->isSame(theObject))) {
619         aRefAttr->setObject(theObject);
620       }
621     }
622   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
623     AttributeSelectionPtr aSelectAttr =
624                              std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
625     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
626     if (aSelectAttr.get() != NULL) {
627       aSelectAttr->setValue(aResult, theShape, theTemporarily);
628     }
629   }
630   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
631     AttributeSelectionListPtr aSelectionListAttr =
632                          std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
633     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
634     if (!theCheckIfAttributeHasObject ||
635         !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
636       aSelectionListAttr->append(aResult, theShape, theTemporarily);
637   }
638   else if (aType == ModelAPI_AttributeRefList::typeId()) {
639     AttributeRefListPtr aRefListAttr =
640       std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
641     if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject)) {
642       if (theObject.get())
643         aRefListAttr->append(theObject);
644       else
645         isDone = false;
646     }
647   }
648   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
649     AttributeRefAttrListPtr aRefAttrListAttr =
650       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
651     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
652
653     if (anAttribute.get()) {
654       if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
655         aRefAttrListAttr->append(anAttribute);
656     }
657     else {
658       if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject)) {
659         if (theObject.get())
660           aRefAttrListAttr->append(theObject);
661         else
662           isDone = false;
663       }
664     }
665   }
666   return isDone;
667 }
668
669 GeomShapePtr getShape(const AttributePtr& theAttribute, ModuleBase_IWorkshop* theWorkshop)
670 {
671   GeomShapePtr aShape;
672   if (!theAttribute.get())
673     return aShape;
674
675   std::string aType = theAttribute->attributeType();
676   if (aType == ModelAPI_AttributeReference::typeId()) {
677   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
678     AttributeRefAttrPtr aRefAttr =
679       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
680     if (aRefAttr.get() && !aRefAttr->isObject()) {
681       AttributePtr anAttribute = aRefAttr->attr();
682       aShape = theWorkshop->module()->findShape(anAttribute);
683     }
684   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
685     AttributeSelectionPtr aSelectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>
686                                                                                  (theAttribute);
687     aShape = aSelectAttr->value();
688   }
689   else // Geom2D point processing
690     aShape = theWorkshop->module()->findShape(theAttribute);
691   return aShape;
692 }
693
694 void flushUpdated(ObjectPtr theObject)
695 {
696   blockUpdateViewer(true);
697
698   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
699
700   blockUpdateViewer(false);
701 }
702
703 void blockUpdateViewer(const bool theValue)
704 {
705   // the viewer update should be blocked in order to avoid the temporary feature content
706   // when the solver processes the feature, the redisplay message can be flushed
707   // what caused the display in the viewer preliminary states of object
708   // e.g. fillet feature, angle value change
709   std::shared_ptr<Events_Message> aMsg;
710   if (theValue) {
711     aMsg = std::shared_ptr<Events_Message>(
712         new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)));
713   }
714   else {
715     // the viewer update should be unblocked
716     aMsg = std::shared_ptr<Events_Message>(
717         new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)));
718   }
719   Events_Loop::loop()->send(aMsg);
720 }
721
722 QString wrapTextByWords(const QString& theValue, QWidget* theWidget,
723                                           int theMaxLineInPixels)
724 {
725   static QFontMetrics tfm(theWidget ? theWidget->font() : QApplication::font());
726   static qreal phi = 2.618;
727
728   QRect aBounds = tfm.boundingRect(theValue);
729   if(aBounds.width() <= theMaxLineInPixels)
730     return theValue;
731
732   qreal s = aBounds.width() * aBounds.height();
733   qreal aGoldWidth = sqrt(s*phi);
734
735   QStringList aWords = theValue.split(" ", QString::SkipEmptyParts);
736   QStringList aLines;
737   int n = aWords.count();
738   QString aLine;
739   for (int i = 0; i < n; i++) {
740     QString aLineExt = aLine + " " + aWords[i];
741     qreal anWidthNonExt = tfm.boundingRect(aLine).width();
742     qreal anWidthExt = tfm.boundingRect(aLineExt).width();
743     qreal aDeltaNonExt = fabs(anWidthNonExt-aGoldWidth);
744     qreal aDeltaExt    = fabs(anWidthExt-aGoldWidth);
745     if(aDeltaNonExt < aDeltaExt) {
746       // new line
747       aLines.append(aLine);
748       aLine = aWords[i];
749     }
750     else
751       aLine = aLineExt;
752   }
753
754   if(!aLine.isEmpty())
755     aLines.append(aLine);
756
757   QString aResult = aLines.join("\n");
758   return aResult;
759 }
760
761 //**************************************************************
762 QLocale doubleLocale()
763 {
764   // VSR 01/07/2010: Disable thousands separator for spin box
765   // (to avoid inconsistency of double-2-string and string-2-double conversion)
766   QLocale aLocale;
767   aLocale.setNumberOptions(aLocale.numberOptions() |
768                            QLocale::OmitGroupSeparator |
769                            QLocale::RejectGroupSeparator);
770   return aLocale;
771 }
772
773 //**************************************************************
774 void refsToFeatureInFeatureDocument(const ObjectPtr& theObject,
775                                     std::set<FeaturePtr>& theRefFeatures)
776 {
777   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
778   if (aFeature.get()) {
779     DocumentPtr aFeatureDoc = aFeature->document();
780     // 1. find references in the current document
781     aFeatureDoc->refsToFeature(aFeature, theRefFeatures, false);
782   }
783 }
784
785
786 //**************************************************************
787 /*bool isSubOfComposite(const ObjectPtr& theObject)
788 {
789   bool isSub = false;
790   std::set<FeaturePtr> aRefFeatures;
791   refsToFeatureInFeatureDocument(theObject, aRefFeatures);
792   std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
793                                        aLast = aRefFeatures.end();
794   for (; anIt != aLast && !isSub; anIt++) {
795     isSub = isSubOfComposite(theObject, *anIt);
796   }
797   return isSub;
798 }*/
799
800 //**************************************************************
801 /*bool isSubOfComposite(const ObjectPtr& theObject, const FeaturePtr& theFeature)
802 {
803   bool isSub = false;
804   CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
805   if (aComposite.get()) {
806     isSub = aComposite->isSub(theObject);
807     // the recursive is possible, the parameters are sketch circle and extrusion cut. They are
808     // separated by composite sketch feature
809     if (!isSub) {
810       int aNbSubs = aComposite->numberOfSubs();
811       for (int aSub = 0; aSub < aNbSubs && !isSub; aSub++) {
812         isSub = isSubOfComposite(theObject, aComposite->subFeature(aSub));
813       }
814     }
815   }
816   return isSub;
817 }*/
818
819 //**************************************************************
820 ResultPtr firstResult(const ObjectPtr& theObject)
821 {
822   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
823   if (!aResult.get()) {
824     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
825     if (aFeature.get())
826       aResult = aFeature->firstResult();
827   }
828   return aResult;
829 }
830
831 //**************************************************************
832 bool isFeatureOfResult(const FeaturePtr& theFeature, const std::string& theGroupOfResult)
833 {
834   bool isResult = false;
835
836   if (!theFeature->data()->isValid())
837     return isResult;
838
839   ResultPtr aFirstResult = theFeature->firstResult();
840   if (!aFirstResult.get())
841     return isResult;
842
843   return aFirstResult->groupName() == theGroupOfResult;
844 }
845
846 //**************************************************************
847 bool hasModuleDocumentFeature(const std::set<FeaturePtr>& theFeatures)
848 {
849   bool aFoundModuleDocumentObject = false;
850   DocumentPtr aModuleDoc = ModelAPI_Session::get()->moduleDocument();
851
852   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(), aLast = theFeatures.end();
853   for (; anIt != aLast && !aFoundModuleDocumentObject; anIt++) {
854     FeaturePtr aFeature = *anIt;
855     ResultPtr aResult = ModuleBase_Tools::firstResult(aFeature);
856     if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group())
857       continue;
858     aFoundModuleDocumentObject = aFeature->document() == aModuleDoc;
859   }
860
861   return aFoundModuleDocumentObject;
862 }
863
864 //**************************************************************
865 bool askToDelete(const std::set<FeaturePtr> theFeatures,
866                  const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
867                  QWidget* theParent,
868                  std::set<FeaturePtr>& theReferencesToDelete,
869                  const std::string& thePrefixInfo)
870 {
871   QString aNotActivatedDocWrn;
872   std::string aNotActivatedNames;
873   if (!ModelAPI_Tools::allDocumentsActivated(aNotActivatedNames)) {
874     if (ModuleBase_Tools::hasModuleDocumentFeature(theFeatures))
875       aNotActivatedDocWrn =
876         QObject::tr("Selected objects can be used in Part documents which are not loaded:%1.\n")
877                             .arg(aNotActivatedNames.c_str());
878   }
879
880   std::set<FeaturePtr> aFeaturesRefsTo;
881   std::set<FeaturePtr> aFeaturesRefsToParameter;
882   std::set<FeaturePtr> aParameterFeatures;
883   QStringList aPartFeatureNames;
884   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
885                                        aLast = theFeatures.end();
886   // separate features to references to parameter features and references to others
887   for (; anIt != aLast; anIt++) {
888     FeaturePtr aFeature = *anIt;
889     if (theReferences.find(aFeature) == theReferences.end())
890       continue;
891
892     if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
893       aPartFeatureNames.append(aFeature->name().c_str());
894
895     std::set<FeaturePtr> aRefFeatures;
896     std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
897     std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
898     for (; aRefIt != aRefLast; aRefIt++) {
899       FeaturePtr aRefFeature = *aRefIt;
900       if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
901           aRefFeatures.find(aRefFeature) == aRefFeatures.end()) // it is not added
902         aRefFeatures.insert(aRefFeature);
903     }
904
905     if (isFeatureOfResult(aFeature, ModelAPI_ResultParameter::group())) {
906       aFeaturesRefsToParameter.insert(aRefFeatures.begin(), aRefFeatures.end());
907       aParameterFeatures.insert(aFeature);
908     }
909     else {
910       theReferencesToDelete.insert(aRefFeatures.begin(), aRefFeatures.end());
911     }
912   }
913
914   std::set<FeaturePtr> aFeaturesRefsToParameterOnly;
915   anIt = aFeaturesRefsToParameter.begin();
916   aLast = aFeaturesRefsToParameter.end();
917   // separate features to references to parameter features and references to others
918   QStringList aParamFeatureNames;
919   for (; anIt != aLast; anIt++) {
920     FeaturePtr aFeature = *anIt;
921     if (theReferencesToDelete.find(aFeature) == theReferencesToDelete.end()) {
922       aFeaturesRefsToParameterOnly.insert(aFeature);
923       aParamFeatureNames.append(aFeature->name().c_str());
924     }
925   }
926   aParamFeatureNames.sort();
927   QStringList anOtherFeatureNames;
928   anIt = theReferencesToDelete.begin();
929   aLast = theReferencesToDelete.end();
930   for (; anIt != aLast; anIt++) {
931     FeaturePtr aFeature = *anIt;
932     if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
933       aPartFeatureNames.append(aFeature->name().c_str());
934     else
935       anOtherFeatureNames.append(aFeature->name().c_str());
936   }
937   aPartFeatureNames.sort();
938   anOtherFeatureNames.sort();
939
940   bool aCanReplaceParameters = !aFeaturesRefsToParameterOnly.empty();
941
942   QMessageBox aMessageBox(theParent);
943   aMessageBox.setWindowTitle(QObject::tr("Delete features"));
944   aMessageBox.setIcon(QMessageBox::Warning);
945   aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
946   aMessageBox.setDefaultButton(QMessageBox::No);
947
948   QString aText;
949   if (!thePrefixInfo.empty())
950     aText = thePrefixInfo.c_str();
951   QString aSep = ", ";
952   if (!aPartFeatureNames.empty()) {
953     aText += QString(QObject::tr("The following parts will be deleted: %1.\n"))
954              .arg(aPartFeatureNames.join(aSep));
955   }
956   if (!aNotActivatedDocWrn.isEmpty())
957     aText += aNotActivatedDocWrn;
958   if (!anOtherFeatureNames.empty()) {
959     const char* aMsg = "Features are used in the following features: %1.\nThese "
960                        "features will be deleted.\n";
961     aText += QString(QObject::tr(aMsg))
962                      .arg(anOtherFeatureNames.join(aSep));
963   }
964   if (!aParamFeatureNames.empty()) {
965     const char* aMsg = "Parameters are used in the following features: %1.\nThese features will "
966                        "be deleted.\nOr parameters could be replaced by their values.\n";
967     aText += QString(QObject::tr(aMsg))
968                      .arg(aParamFeatureNames.join(aSep));
969     QPushButton *aReplaceButton =
970       aMessageBox.addButton(QObject::tr("Replace"), QMessageBox::ActionRole);
971   }
972
973   if (!aText.isEmpty()) {
974     aText += "Would you like to continue?";
975     aMessageBox.setText(aText);
976     aMessageBox.exec();
977     QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
978
979     if (aButtonRole == QMessageBox::NoRole)
980       return false;
981
982     if (aButtonRole == QMessageBox::ActionRole) {
983       foreach (FeaturePtr aObj, aParameterFeatures)
984         ModelAPI_ReplaceParameterMessage::send(aObj, 0);
985     }
986     else
987       theReferencesToDelete.insert(aFeaturesRefsToParameterOnly.begin(),
988                                    aFeaturesRefsToParameterOnly.end());
989   }
990   return true;
991 }
992
993 //**************************************************************
994 void convertToFeatures(const QObjectPtrList& theObjects, std::set<FeaturePtr>& theFeatures)
995 {
996   QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
997   for(; anIt != aLast; anIt++) {
998     ObjectPtr anObject = *anIt;
999     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1000     // for parameter result, use the corresponded reature to be removed
1001     if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1002       aFeature = ModelAPI_Feature::feature(anObject);
1003     }
1004     theFeatures.insert(aFeature);
1005   }
1006 }
1007
1008 QString translate(const Events_InfoMessage& theMessage)
1009 {
1010   QString aMessage;
1011
1012   if (!theMessage.empty()) {
1013     std::string aStr = Config_Translator::translate(theMessage);
1014     if (!aStr.empty()) {
1015       std::string aCodec = Config_Translator::codec(theMessage);
1016       aMessage = QTextCodec::codecForName(aCodec.c_str())->toUnicode(aStr.c_str());
1017     }
1018   }
1019
1020   return aMessage;
1021 }
1022
1023 QString translate(const std::string& theContext, const std::string& theMessage)
1024 {
1025   QString aMessage;
1026
1027   if (!theMessage.empty()) {
1028     std::string aStr = Config_Translator::translate(theContext, theMessage);
1029     if (!aStr.empty()) {
1030       std::string aCodec = Config_Translator::codec(theContext);
1031       aMessage = QTextCodec::codecForName(aCodec.c_str())->toUnicode(aStr.c_str());
1032     }
1033   }
1034
1035   return aMessage;
1036 }
1037
1038 void setPointBallHighlighting(AIS_Shape* theAIS)
1039 {
1040   static Handle(Image_AlienPixMap) aPixMap;
1041   if(aPixMap.IsNull()) {
1042     // Load icon for the presentation
1043     std::string aFile;
1044     char* anEnv = getenv("SHAPER_ROOT_DIR");
1045     if(anEnv) {
1046       aFile = std::string(anEnv) +
1047         FSEP + "share" + FSEP + "salome" + FSEP + "resources" + FSEP + "shaper";
1048     } else {
1049       anEnv = getenv("OPENPARTS_ROOT_DIR");
1050       if (anEnv)
1051         aFile = std::string(anEnv) + FSEP + "resources";
1052     }
1053
1054     aFile += FSEP;
1055     static const std::string aMarkerName = "marker_dot.png";
1056     aFile += aMarkerName;
1057     aPixMap = new Image_AlienPixMap();
1058     if(!aPixMap->Load(aFile.c_str())) {
1059       // The icon for constraint is not found
1060       static const std::string aMsg =
1061         "Error: Point market not found by path: \"" + aFile + "\". Falling back.";
1062       //Events_InfoMessage("ModuleBase_Tools::setPointBallHighlighting", aMsg).send();
1063     }
1064   }
1065
1066   Handle(Graphic3d_AspectMarker3d) anAspect;
1067   Handle(Prs3d_Drawer) aDrawer = theAIS->HilightAttributes();
1068   if(aDrawer->HasOwnPointAspect()) {
1069     Handle(Prs3d_PointAspect) aPntAspect = aDrawer->PointAspect();
1070     if(aPixMap->IsEmpty()) {
1071       anAspect = aPntAspect->Aspect();
1072       anAspect->SetType(Aspect_TOM_BALL);
1073     } else {
1074       if(aPixMap->Format() == Image_PixMap::ImgGray) {
1075         aPixMap->SetFormat (Image_PixMap::ImgAlpha);
1076       } else if(aPixMap->Format() == Image_PixMap::ImgGrayF) {
1077         aPixMap->SetFormat (Image_PixMap::ImgAlphaF);
1078       }
1079       anAspect = new Graphic3d_AspectMarker3d(aPixMap);
1080       aPntAspect->SetAspect(anAspect);
1081     }
1082     aDrawer->SetPointAspect(aPntAspect);
1083     theAIS->SetHilightAttributes(aDrawer);
1084   }
1085 }
1086
1087 } // namespace ModuleBase_Tools
1088
1089