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