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