Salome HOME
37e6500b4d58f567de51b101f825e315a57e3f16
[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
16 #include <ModelAPI_Attribute.h>
17 #include <ModelAPI_AttributeRefAttr.h>
18 #include <ModelAPI_AttributeReference.h>
19 #include <ModelAPI_AttributeSelection.h>
20 #include <ModelAPI_AttributeSelectionList.h>
21 #include <ModelAPI_AttributeRefList.h>
22 #include <ModelAPI_AttributeRefAttrList.h>
23 #include <ModelAPI_ResultPart.h>
24 #include <Events_Loop.h>
25
26 #include <ModelAPI_Data.h>
27 #include <ModelAPI_Result.h>
28 #include <ModelAPI_ResultCompSolid.h>
29 #include <ModelAPI_ResultParameter.h>
30 #include <ModelAPI_Tools.h>
31 #include <ModelAPI_Session.h>
32 #include <ModelAPI_Events.h>
33
34 #include <TopoDS_Iterator.hxx>
35
36 #include <GeomDataAPI_Point2D.h>
37 #include <Events_Error.h>
38
39 #include <Config_PropManager.h>
40
41 #include <QWidget>
42 #include <QLayout>
43 #include <QPainter>
44 #include <QBitmap>
45 #include <QDoubleSpinBox>
46 #include <QGraphicsDropShadowEffect>
47 #include <QColor>
48 #include <QApplication>
49 #include <QMessageBox>
50 #include <QAction>
51
52 #include <sstream>
53 #include <string>
54
55 const double tolerance = 1e-7;
56
57 //#define DEBUG_ACTIVATE_WINDOW
58 //#define DEBUG_SET_FOCUS
59
60 namespace ModuleBase_Tools {
61
62 //******************************************************************
63
64 //******************************************************************
65
66 void adjustMargins(QWidget* theWidget)
67 {
68   if(!theWidget)
69     return;
70   adjustMargins(theWidget->layout());
71 }
72
73 void adjustMargins(QLayout* theLayout)
74 {
75   if(!theLayout)
76     return;
77   theLayout->setContentsMargins(2, 5, 2, 5);
78   theLayout->setSpacing(4);
79 }
80
81 void zeroMargins(QWidget* theWidget)
82 {
83   if(!theWidget)
84     return;
85   zeroMargins(theWidget->layout());
86 }
87
88 void zeroMargins(QLayout* theLayout)
89 {
90   if(!theLayout)
91     return;
92   theLayout->setContentsMargins(0, 0, 0, 0);
93   theLayout->setSpacing(5);
94 }
95
96 void activateWindow(QWidget* theWidget, const QString& theInfo)
97 {
98   theWidget->activateWindow();
99
100 #ifdef DEBUG_ACTIVATE_WINDOW
101   qDebug(QString("activateWindow: %1").arg(theInfo).toStdString().c_str());
102 #endif
103 }
104
105 void setFocus(QWidget* theWidget, const QString& theInfo)
106 {
107   theWidget->setFocus();
108
109 #ifdef DEBUG_SET_FOCUS
110   qDebug(QString("setFocus: %1").arg(theInfo).toStdString().c_str());
111 #endif
112 }
113
114 void setShadowEffect(QWidget* theWidget, const bool isSetEffect)
115 {
116   if (isSetEffect) {
117     QGraphicsDropShadowEffect* aGlowEffect = new QGraphicsDropShadowEffect();
118     aGlowEffect->setOffset(.0);
119     aGlowEffect->setBlurRadius(10.0);
120     aGlowEffect->setColor(QColor(0, 170, 255)); // Light-blue color, #00AAFF
121     theWidget->setGraphicsEffect(aGlowEffect);
122   }
123   else {
124     QGraphicsEffect* anEffect = theWidget->graphicsEffect();
125     if(anEffect)
126     anEffect->deleteLater();
127     theWidget->setGraphicsEffect(NULL);
128   }
129 }
130
131 QPixmap composite(const QString& theAdditionalIcon, const QString& theIcon)
132 {
133   QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
134   QImage anAditional(theAdditionalIcon);
135
136   if (anIcon.isNull())
137     return QPixmap();
138
139   int anAddWidth = anAditional.width();
140   int anAddHeight = anAditional.height();
141
142   int aWidth = anIcon.width();
143   int aHeight = anIcon.height();
144
145   int aStartWidthPos = aWidth - anAddWidth - 1;
146   int aStartHeightPos = aHeight - anAddHeight - 1;
147
148   for (int i = 0; i < anAddWidth && i + aStartWidthPos < aWidth; i++)
149   {
150     for (int j = 0; j < anAddHeight && j + aStartHeightPos < aHeight; j++)
151     {
152       if (qAlpha(anAditional.pixel(i, j)) > 0)
153         anIcon.setPixel(i + aStartWidthPos, j + aStartHeightPos, anAditional.pixel(i, j));
154     }
155   }
156   return QPixmap::fromImage(anIcon);
157 }
158
159 QPixmap lighter(const QString& theIcon, const int theLighterValue)
160 {
161   QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
162   if (anIcon.isNull())
163     return QPixmap();
164
165   QImage aResult = ModuleBase_IconFactory::loadImage(theIcon);
166   for (int i = 0; i < anIcon.width(); i++)
167   {
168     for (int j = 0; j < anIcon.height(); j++)
169     {
170       QRgb anRgb = anIcon.pixel(i, j);
171       QColor aPixelColor(qRed(anRgb), qGreen(anRgb), qBlue(anRgb),
172                          qAlpha(aResult.pixel(i, j)));
173
174       QColor aLighterColor = aPixelColor.lighter(theLighterValue);
175       aResult.setPixel(i, j, qRgba(aLighterColor.red(), aLighterColor.green(),
176                                     aLighterColor.blue(), aLighterColor.alpha()));
177     }
178   }
179   return QPixmap::fromImage(aResult);
180 }
181
182 void setSpinText(ModuleBase_ParamSpinBox* theSpin, const QString& theText)
183 {
184   if (theSpin->text() == theText) 
185     return;
186   // In order to avoid extra text setting because it will
187   // reset cursor position in control
188   bool isBlocked = theSpin->blockSignals(true);
189   theSpin->setText(theText);
190   theSpin->blockSignals(isBlocked);
191 }
192
193 void setSpinValue(QDoubleSpinBox* theSpin, double theValue)
194 {
195   if (fabs(theSpin->value() - theValue) < tolerance)
196     return;
197   bool isBlocked = theSpin->blockSignals(true);
198   theSpin->setValue(theValue);
199   theSpin->blockSignals(isBlocked);
200 }
201
202 void setSpinValue(ModuleBase_ParamSpinBox* theSpin, double theValue)
203 {
204   if (fabs(theSpin->value() - theValue) < tolerance)
205     return;
206   bool isBlocked = theSpin->blockSignals(true);
207   theSpin->setValue(theValue);
208   theSpin->blockSignals(isBlocked);
209 }
210
211 void setSpinText(ModuleBase_ParamIntSpinBox* theSpin, const QString& theText)
212 {
213   // In order to avoid extra text setting because it will
214   // reset cursor position in control
215   if (theSpin->text() == theText)
216     return;
217   bool isBlocked = theSpin->blockSignals(true);
218   theSpin->setText(theText);
219   theSpin->blockSignals(isBlocked);
220 }
221
222 void setSpinValue(ModuleBase_ParamIntSpinBox* theSpin, int theValue)
223 {
224   if (theSpin->value() == theValue)
225     return;
226   bool isBlocked = theSpin->blockSignals(true);
227   theSpin->setValue(theValue);
228   theSpin->blockSignals(isBlocked);
229 }
230
231 QAction* createAction(const QIcon& theIcon, const QString& theText,
232                       QObject* theParent, const QObject* theReceiver,
233                       const char* theMember, const QString& theToolTip,
234                       const QString& theStatusTip)
235 {
236   QAction* anAction = new QAction(theIcon, theText, theParent);
237   anAction->setToolTip(theToolTip.isEmpty() ? theText : theToolTip);
238   anAction->setStatusTip(!theStatusTip.isEmpty() ? theStatusTip :
239                                                    (!theToolTip.isEmpty() ? theToolTip : theText));
240   if (theReceiver)
241     QObject::connect(anAction, SIGNAL(triggered(bool)), theReceiver, theMember);
242
243   return anAction;
244 }
245
246 QString objectInfo(const ObjectPtr& theObj, const bool isUseAttributesInfo)
247 {
248   QString aFeatureStr = "feature";
249   if (!theObj.get())
250     return aFeatureStr;
251
252   std::ostringstream aPtrStr;
253   aPtrStr << "[" << theObj.get() << "]";
254
255   ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theObj);
256   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
257   if(aRes.get()) {
258     aFeatureStr.append(QString("(result%1)").arg(aPtrStr.str().c_str()).toStdString() .c_str());
259     if (aRes->isDisabled())
260       aFeatureStr.append("[disabled]");
261     if (aRes->isConcealed())
262       aFeatureStr.append("[concealed]");
263     if (ModelAPI_Tools::hasSubResults(aRes))
264       aFeatureStr.append("[hasSubResults]");
265
266     aFeature = ModelAPI_Feature::feature(aRes);
267   }
268   else
269     aFeatureStr.append(aPtrStr.str().c_str());
270
271   if (aFeature.get()) {
272     aFeatureStr.append(QString(": %1").arg(aFeature->getKind().c_str()).toStdString().c_str());
273     if (aFeature->data()->isValid()) {
274       aFeatureStr.append(QString(", name=%1").arg(aFeature->data()->name().c_str()).toStdString()
275                                                                                        .c_str());
276     }
277     if (isUseAttributesInfo) {
278       std::list<AttributePtr> anAttrs = aFeature->data()->attributes("");
279       std::list<AttributePtr>::const_iterator anIt = anAttrs.begin(), aLast = anAttrs.end();
280       QStringList aValues;
281       for(; anIt != aLast; anIt++) {
282         AttributePtr anAttr = *anIt;
283         QString aValue = "not defined";
284         std::string aType = anAttr->attributeType();
285         if (aType == GeomDataAPI_Point2D::typeId()) {
286           std::shared_ptr<GeomDataAPI_Point2D> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
287                                                                                          anAttr);
288           if (aPoint.get())
289             aValue = QString("(%1, %2)").arg(aPoint->x()).arg(aPoint->y());
290         }
291         else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
292         }
293
294         aValues.push_back(QString("%1: %2").arg(anAttr->id().c_str()).arg(aValue).toStdString().c_str());
295       }
296       if (!aValues.empty())
297         aFeatureStr.append(QString(", attributes: %1").arg(aValues.join(", ").toStdString().c_str()));
298     }
299   }
300
301   return aFeatureStr;
302 }
303
304 typedef QMap<QString, TopAbs_ShapeEnum> ShapeTypes;
305 static ShapeTypes MyShapeTypes;
306
307 TopAbs_ShapeEnum shapeType(const QString& theType)
308 {
309   if (MyShapeTypes.count() == 0) {
310     MyShapeTypes["face"] = TopAbs_FACE;
311     MyShapeTypes["faces"] = TopAbs_FACE;
312     MyShapeTypes["vertex"] = TopAbs_VERTEX;
313     MyShapeTypes["vertices"] = TopAbs_VERTEX;
314     MyShapeTypes["wire"] = TopAbs_WIRE;
315     MyShapeTypes["wires"] = TopAbs_WIRE;
316     MyShapeTypes["edge"] = TopAbs_EDGE;
317     MyShapeTypes["edges"] = TopAbs_EDGE;
318     MyShapeTypes["shell"] = TopAbs_SHELL;
319     MyShapeTypes["solid"] = TopAbs_SOLID;
320     MyShapeTypes["solids"] = TopAbs_SOLID;
321     MyShapeTypes["objects"] = TopAbs_SHAPE;
322   }
323   QString aType = theType.toLower();
324   if (MyShapeTypes.contains(aType))
325     return MyShapeTypes[aType];
326   Events_Error::send("Shape type defined in XML is not implemented!");
327   return TopAbs_SHAPE;
328 }
329
330 void checkObjects(const QObjectPtrList& theObjects, bool& hasResult, bool& hasFeature,
331                   bool& hasParameter, bool& hasCompositeOwner)
332 {
333   hasResult = false;
334   hasFeature = false;
335   hasParameter = false;
336   hasCompositeOwner = false;
337   foreach(ObjectPtr aObj, theObjects) {
338     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
339     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
340     ResultParameterPtr aConstruction = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aResult);
341
342     hasResult |= (aResult.get() != NULL);
343     hasFeature |= (aFeature.get() != NULL);
344     hasParameter |= (aConstruction.get() != NULL);
345     if (hasFeature) 
346       hasCompositeOwner |= (ModelAPI_Tools::compositeOwner(aFeature) != NULL);
347     if (hasFeature && hasResult  && hasParameter && hasCompositeOwner)
348       break;
349   }
350 }
351
352 void setDefaultDeviationCoefficient(const TopoDS_Shape& theShape,
353                                     const Handle(Prs3d_Drawer)& theDrawer)
354 {
355   if (theShape.IsNull())
356     return;
357   TopAbs_ShapeEnum aType = theShape.ShapeType();
358   if ((aType == TopAbs_EDGE) || (aType == TopAbs_WIRE)) 
359     theDrawer->SetDeviationCoefficient(1.e-4);
360 }
361
362 Quantity_Color color(const std::string& theSection,
363                      const std::string& theName,
364                      const std::string& theDefault)
365 {
366   std::vector<int> aColor = Config_PropManager::color(theSection, theName, theDefault);
367   return Quantity_Color(aColor[0] / 255., aColor[1] / 255., aColor[2] / 255., Quantity_TOC_RGB);
368 }
369
370 ObjectPtr getObject(const AttributePtr& theAttribute)
371 {
372   ObjectPtr anObject;
373   std::string anAttrType = theAttribute->attributeType();
374   if (anAttrType == ModelAPI_AttributeRefAttr::typeId()) {
375     AttributeRefAttrPtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
376     if (anAttr != NULL && anAttr->isObject())
377       anObject = anAttr->object();
378   }
379   if (anAttrType == ModelAPI_AttributeSelection::typeId()) {
380     AttributeSelectionPtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
381     if (anAttr != NULL)
382       anObject = anAttr->context();
383   }
384   if (anAttrType == ModelAPI_AttributeReference::typeId()) {
385     AttributeReferencePtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
386     if (anAttr.get() != NULL)
387       anObject = anAttr->value();
388   }
389   return anObject;
390 }
391
392 TopAbs_ShapeEnum getCompoundSubType(const TopoDS_Shape& theShape)
393 {
394   TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
395
396   // for compounds check sub-shapes: it may be compound of needed type:
397   // Booleans may produce compounds of Solids
398   if (aShapeType == TopAbs_COMPOUND) {
399     for(TopoDS_Iterator aSubs(theShape); aSubs.More(); aSubs.Next()) {
400       if (!aSubs.Value().IsNull()) {
401         TopAbs_ShapeEnum aSubType = aSubs.Value().ShapeType();
402         if (aSubType == TopAbs_COMPOUND) { // compound of compound(s)
403           aShapeType = TopAbs_COMPOUND;
404           break;
405         }
406         if (aShapeType == TopAbs_COMPOUND) {
407           aShapeType = aSubType;
408         } else if (aShapeType != aSubType) { // compound of shapes of different types
409           aShapeType = TopAbs_COMPOUND;
410           break;
411         }
412       }
413     }
414   }
415   return aShapeType;
416 }
417
418 void getParameters(QStringList& theParameters)
419 {
420   theParameters.clear();
421
422   SessionPtr aSession = ModelAPI_Session::get();
423   std::list<DocumentPtr> aDocList;
424   DocumentPtr anActiveDocument = aSession->activeDocument();
425   DocumentPtr aRootDocument = aSession->moduleDocument();
426   aDocList.push_back(anActiveDocument);
427   if (anActiveDocument != aRootDocument) {
428     aDocList.push_back(aRootDocument);
429   }
430   std::string aGroupId = ModelAPI_ResultParameter::group();
431   for(std::list<DocumentPtr>::const_iterator it = aDocList.begin(); it != aDocList.end(); ++it) {
432     DocumentPtr aDocument = *it;
433     int aSize = aDocument->size(aGroupId);
434     for (int i = 0; i < aSize; i++) {
435       ObjectPtr anObject = aDocument->object(aGroupId, i);
436       std::string aParameterName = anObject->data()->name();
437       theParameters.append(aParameterName.c_str());
438     }
439   }
440 }
441
442 std::string findGreedAttribute(ModuleBase_IWorkshop* theWorkshop, const FeaturePtr& theFeature)
443 {
444   std::string anAttributeId;
445
446   std::string aXmlCfg, aDescription;
447   theWorkshop->module()->getXMLRepresentation(theFeature->getKind(), aXmlCfg, aDescription);
448
449   ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
450   std::string anAttributeTitle;
451   aFactory.getGreedAttribute(anAttributeId);
452
453   return anAttributeId;
454 }
455
456 bool hasObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
457                const std::shared_ptr<GeomAPI_Shape>& theShape,
458                ModuleBase_IWorkshop* theWorkshop,
459                const bool theTemporarily)
460 {
461   bool aHasObject = false;
462   if (!theAttribute.get())
463     return aHasObject;
464
465   std::string aType = theAttribute->attributeType();
466   if (aType == ModelAPI_AttributeReference::typeId()) {
467     AttributeReferencePtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
468     ObjectPtr aObject = aRef->value();
469     aHasObject = aObject && aObject->isSame(theObject);
470     //if (!(aObject && aObject->isSame(theObject))) {
471     //  aRef->setValue(theObject);
472     //}
473   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
474     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
475
476     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
477     if (anAttribute.get()) {
478       //aRefAttr->setAttr(anAttribute);
479     }
480     else {
481       ObjectPtr aObject = aRefAttr->object();
482       aHasObject = aObject && aObject->isSame(theObject);
483       //if (!(aObject && aObject->isSame(theObject))) {
484       //  aRefAttr->setObject(theObject);
485       //}
486     }
487   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
488     /*AttributeSelectionPtr aSelectAttr =
489                              std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
490     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
491     if (aSelectAttr.get() != NULL) {
492       aSelectAttr->setValue(aResult, theShape, theTemporarily);
493     }*/
494   }
495   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
496     AttributeSelectionListPtr aSelectionListAttr =
497                          std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
498     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
499     aHasObject = aSelectionListAttr->isInList(aResult, theShape, theTemporarily);
500     //if (!theCheckIfAttributeHasObject || !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
501     //  aSelectionListAttr->append(aResult, theShape, theTemporarily);
502   }
503   else if (aType == ModelAPI_AttributeRefList::typeId()) {
504     AttributeRefListPtr aRefListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
505     aHasObject = aRefListAttr->isInList(theObject);
506     //if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
507     //  aRefListAttr->append(theObject);
508   }
509   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
510     AttributeRefAttrListPtr aRefAttrListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
511     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
512
513     if (anAttribute.get()) {
514       aHasObject = aRefAttrListAttr->isInList(anAttribute);
515       //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
516       //  aRefAttrListAttr->append(anAttribute);
517     }
518     else {
519       aHasObject = aRefAttrListAttr->isInList(theObject);
520       //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
521       //  aRefAttrListAttr->append(theObject);
522     }
523   }
524   return aHasObject;
525 }
526
527 void setObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
528                const GeomShapePtr& theShape, ModuleBase_IWorkshop* theWorkshop,
529                const bool theTemporarily, const bool theCheckIfAttributeHasObject)
530 {
531   if (!theAttribute.get())
532     return;
533
534   std::string aType = theAttribute->attributeType();
535   if (aType == ModelAPI_AttributeReference::typeId()) {
536     AttributeReferencePtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
537     ObjectPtr aObject = aRef->value();
538     if (!(aObject && aObject->isSame(theObject))) {
539       aRef->setValue(theObject);
540     }
541   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
542     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
543
544     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
545     if (anAttribute.get())
546       aRefAttr->setAttr(anAttribute);
547     else {
548       ObjectPtr aObject = aRefAttr->object();
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     if (!theCheckIfAttributeHasObject || !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
566       aSelectionListAttr->append(aResult, theShape, theTemporarily);
567   }
568   else if (aType == ModelAPI_AttributeRefList::typeId()) {
569     AttributeRefListPtr aRefListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
570     if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
571       aRefListAttr->append(theObject);
572   }
573   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
574     AttributeRefAttrListPtr aRefAttrListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
575     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
576
577     if (anAttribute.get()) {
578       if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
579         aRefAttrListAttr->append(anAttribute);
580     }
581     else {
582       if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
583         aRefAttrListAttr->append(theObject);
584     }
585   }
586 }
587
588 GeomShapePtr getShape(const AttributePtr& theAttribute, ModuleBase_IWorkshop* theWorkshop)
589 {
590   GeomShapePtr aShape;
591   if (!theAttribute.get())
592     return aShape;
593
594   std::string aType = theAttribute->attributeType();
595   if (aType == ModelAPI_AttributeReference::typeId()) {
596   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
597     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
598     if (aRefAttr.get() && !aRefAttr->isObject()) {
599       AttributePtr anAttribute = aRefAttr->attr();
600       aShape = theWorkshop->module()->findShape(anAttribute);
601     }
602   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
603     AttributeSelectionPtr aSelectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>
604                                                                                  (theAttribute);
605     aShape = aSelectAttr->value();
606   }
607   return aShape;
608 }
609
610 void flushUpdated(ObjectPtr theObject)
611 {
612   blockUpdateViewer(true);
613
614   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
615
616   blockUpdateViewer(false);
617 }
618
619 void blockUpdateViewer(const bool theValue)
620 {
621   // the viewer update should be blocked in order to avoid the temporary feature content
622   // when the solver processes the feature, the redisplay message can be flushed
623   // what caused the display in the viewer preliminary states of object
624   // e.g. fillet feature, angle value change
625   std::shared_ptr<Events_Message> aMsg;
626   if (theValue) {
627     aMsg = std::shared_ptr<Events_Message>(
628         new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)));
629   }
630   else {
631     // the viewer update should be unblocked
632     aMsg = std::shared_ptr<Events_Message>(
633         new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)));
634   }
635   Events_Loop::loop()->send(aMsg);
636 }
637
638 QString wrapTextByWords(const QString& theValue, QWidget* theWidget,
639                                           int theMaxLineInPixels)
640 {
641   static QFontMetrics tfm(theWidget ? theWidget->font() : QApplication::font());
642   static qreal phi = 2.618;
643
644   QRect aBounds = tfm.boundingRect(theValue);
645   if(aBounds.width() <= theMaxLineInPixels)
646     return theValue;
647
648   qreal s = aBounds.width() * aBounds.height();
649   qreal aGoldWidth = sqrt(s*phi);
650
651   QStringList aWords = theValue.split(" ", QString::SkipEmptyParts);
652   QStringList aLines;
653   int n = aWords.count();
654   QString aLine;
655   for (int i = 0; i < n; i++) {
656     QString aLineExt = aLine + " " + aWords[i];
657     qreal anWidthNonExt = tfm.boundingRect(aLine).width();
658     qreal anWidthExt = tfm.boundingRect(aLineExt).width();
659     qreal aDeltaNonExt = fabs(anWidthNonExt-aGoldWidth);
660     qreal aDeltaExt    = fabs(anWidthExt-aGoldWidth);
661     if(aDeltaNonExt < aDeltaExt) {
662       // new line
663       aLines.append(aLine);
664       aLine = aWords[i];
665     }
666     else
667       aLine = aLineExt;
668   }
669
670   if(!aLine.isEmpty())
671     aLines.append(aLine);
672
673   QString aResult = aLines.join("\n");
674   return aResult;
675 }
676
677 //**************************************************************
678 void refsToFeatureInFeatureDocument(const ObjectPtr& theObject, std::set<FeaturePtr>& theRefFeatures)
679 {
680   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
681   if (aFeature.get()) {
682     DocumentPtr aFeatureDoc = aFeature->document();
683     // 1. find references in the current document
684     aFeatureDoc->refsToFeature(aFeature, theRefFeatures, false);
685   }
686 }
687
688
689 //**************************************************************
690 bool isSubOfComposite(const ObjectPtr& theObject)
691 {
692   bool isSub = false;
693   std::set<FeaturePtr> aRefFeatures;
694   refsToFeatureInFeatureDocument(theObject, aRefFeatures);
695   std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
696                                        aLast = aRefFeatures.end();
697   for (; anIt != aLast && !isSub; anIt++) {
698     isSub = isSubOfComposite(theObject, *anIt);
699   }
700   return isSub;
701 }
702
703 //**************************************************************
704 bool isSubOfComposite(const ObjectPtr& theObject, const FeaturePtr& theFeature)
705 {
706   bool isSub = false;
707   CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
708   if (aComposite.get()) {
709     isSub = aComposite->isSub(theObject);
710     // the recursive is possible, the parameters are sketch circle and extrusion cut. They are
711     // separated by composite sketch feature
712     if (!isSub) {
713       int aNbSubs = aComposite->numberOfSubs();
714       for (int aSub = 0; aSub < aNbSubs && !isSub; aSub++) {
715         isSub = isSubOfComposite(theObject, aComposite->subFeature(aSub));
716       }
717     }
718   }
719   return isSub;
720 }
721
722 //**************************************************************
723 bool isFeatureOfResult(const FeaturePtr& theFeature, const std::string& theGroupOfResult)
724 {
725   bool isResult = false;
726
727   if (!theFeature->data()->isValid())
728     return isResult;
729
730   ResultPtr aFirstResult = theFeature->firstResult();
731   if (!aFirstResult.get())
732     return isResult;
733
734   return aFirstResult->groupName() == theGroupOfResult;
735 }
736
737 //**************************************************************
738 bool askToDelete(const std::set<FeaturePtr> theFeatures,
739                  const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
740                  QWidget* theParent,
741                  std::set<FeaturePtr>& theReferencesToDelete)
742 {
743   std::set<FeaturePtr> aFeaturesRefsTo;
744   std::set<FeaturePtr> aFeaturesRefsToParameter;
745   std::set<FeaturePtr> aParameterFeatures;
746   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
747                                        aLast = theFeatures.end();
748   // separate features to references to parameter features and references to others
749   for (; anIt != aLast; anIt++) {
750     FeaturePtr aFeature = *anIt;
751     if (theReferences.find(aFeature) == theReferences.end())
752       continue;
753
754     std::set<FeaturePtr> aRefFeatures;
755     std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
756     std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
757     for (; aRefIt != aRefLast; aRefIt++) {
758       FeaturePtr aRefFeature = *aRefIt;
759       if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
760           aRefFeatures.find(aRefFeature) == aRefFeatures.end()) // it is not added
761         aRefFeatures.insert(aRefFeature);
762     }
763
764     if (isFeatureOfResult(aFeature, ModelAPI_ResultParameter::group())) {
765       aFeaturesRefsToParameter.insert(aRefFeatures.begin(), aRefFeatures.end());
766       aParameterFeatures.insert(aFeature);
767     }
768     else {
769       theReferencesToDelete.insert(aRefFeatures.begin(), aRefFeatures.end());
770     }
771   }
772
773   std::set<FeaturePtr> aFeaturesRefsToParameterOnly;
774   anIt = aFeaturesRefsToParameter.begin();
775   aLast = aFeaturesRefsToParameter.end();
776   // separate features to references to parameter features and references to others
777   QStringList aParamFeatureNames;
778   for (; anIt != aLast; anIt++) {
779     FeaturePtr aFeature = *anIt;
780     if (theReferencesToDelete.find(aFeature) == theReferencesToDelete.end()) {
781       aFeaturesRefsToParameterOnly.insert(aFeature);
782       aParamFeatureNames.append(aFeature->name().c_str());
783     }
784   }
785   aParamFeatureNames.sort();
786   QStringList aPartFeatureNames, anOtherFeatureNames;
787   anIt = theReferencesToDelete.begin();
788   aLast = theReferencesToDelete.end();
789   for (; anIt != aLast; anIt++) {
790     FeaturePtr aFeature = *anIt;
791     if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
792       aPartFeatureNames.append(aFeature->name().c_str());
793     else
794       anOtherFeatureNames.append(aFeature->name().c_str());
795   }
796   aPartFeatureNames.sort();
797   anOtherFeatureNames.sort();
798
799   bool aCanReplaceParameters = !aFeaturesRefsToParameterOnly.empty();
800
801   QMessageBox aMessageBox(theParent);
802   aMessageBox.setWindowTitle(QObject::tr("Delete features"));
803   aMessageBox.setIcon(QMessageBox::Warning);
804   aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
805   aMessageBox.setDefaultButton(QMessageBox::No);
806
807   QString aText;
808   QString aSep = ", ";
809   if (!aPartFeatureNames.empty())
810     aText += QString(QObject::tr("The following parts will be deleted: %1.\n")).arg(aPartFeatureNames.join(aSep));
811   if (!anOtherFeatureNames.empty())
812     aText += QString(QObject::tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n"))
813                      .arg(anOtherFeatureNames.join(aSep));
814   if (!aParamFeatureNames.empty()) {
815     aText += QString(QObject::tr("Selected parameters are used in the following features: %1.\nThese features will be deleted.\nOr parameters could be replaced by their values.\n"))
816                      .arg(aParamFeatureNames.join(aSep));
817     QPushButton *aReplaceButton = aMessageBox.addButton(QObject::tr("Replace"), QMessageBox::ActionRole);
818   }
819
820   if (!aText.isEmpty()) {
821     aText += "Would you like to continue?";
822     aMessageBox.setText(aText);
823     aMessageBox.exec();
824     QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
825
826     if (aButtonRole == QMessageBox::NoRole)
827       return false;
828
829     if (aButtonRole == QMessageBox::ActionRole) {
830       foreach (FeaturePtr aObj, aParameterFeatures)
831         ModelAPI_ReplaceParameterMessage::send(aObj, 0);
832     }
833     else
834       theReferencesToDelete.insert(aFeaturesRefsToParameterOnly.begin(), aFeaturesRefsToParameterOnly.end());
835   }
836   return true;
837 }
838
839 //**************************************************************
840 void convertToFeatures(const QObjectPtrList& theObjects, std::set<FeaturePtr>& theFeatures)
841 {
842   QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
843   for(; anIt != aLast; anIt++) {
844     ObjectPtr anObject = *anIt;
845     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
846     // for parameter result, use the corresponded reature to be removed
847     if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
848       aFeature = ModelAPI_Feature::feature(anObject);
849     }
850     theFeatures.insert(aFeature);
851   }
852 }
853
854 } // namespace ModuleBase_Tools
855
856