Salome HOME
822640eac33ff7484bc693686c92d47e9bfdae5c
[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["edge"] = TopAbs_EDGE;
316     MyShapeTypes["edges"] = TopAbs_EDGE;
317     MyShapeTypes["shell"] = TopAbs_SHELL;
318     MyShapeTypes["solid"] = TopAbs_SOLID;
319     MyShapeTypes["solids"] = TopAbs_SOLID;
320     MyShapeTypes["objects"] = TopAbs_SHAPE;
321   }
322   QString aType = theType.toLower();
323   if (MyShapeTypes.contains(aType))
324     return MyShapeTypes[aType];
325   Events_Error::send("Shape type defined in XML is not implemented!");
326   return TopAbs_SHAPE;
327 }
328
329 void checkObjects(const QObjectPtrList& theObjects, bool& hasResult, bool& hasFeature,
330                   bool& hasParameter, bool& hasCompositeOwner)
331 {
332   hasResult = false;
333   hasFeature = false;
334   hasParameter = false;
335   hasCompositeOwner = false;
336   foreach(ObjectPtr aObj, theObjects) {
337     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
338     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
339     ResultParameterPtr aConstruction = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aResult);
340
341     hasResult |= (aResult.get() != NULL);
342     hasFeature |= (aFeature.get() != NULL);
343     hasParameter |= (aConstruction.get() != NULL);
344     if (hasFeature) 
345       hasCompositeOwner |= (ModelAPI_Tools::compositeOwner(aFeature) != NULL);
346     if (hasFeature && hasResult  && hasParameter && hasCompositeOwner)
347       break;
348   }
349 }
350
351 void setDefaultDeviationCoefficient(const TopoDS_Shape& theShape,
352                                     const Handle(Prs3d_Drawer)& theDrawer)
353 {
354   if (theShape.IsNull())
355     return;
356   TopAbs_ShapeEnum aType = theShape.ShapeType();
357   if ((aType == TopAbs_EDGE) || (aType == TopAbs_WIRE)) 
358     theDrawer->SetDeviationCoefficient(1.e-4);
359 }
360
361 Quantity_Color color(const std::string& theSection,
362                      const std::string& theName,
363                      const std::string& theDefault)
364 {
365   std::vector<int> aColor = Config_PropManager::color(theSection, theName, theDefault);
366   return Quantity_Color(aColor[0] / 255., aColor[1] / 255., aColor[2] / 255., Quantity_TOC_RGB);
367 }
368
369 ObjectPtr getObject(const AttributePtr& theAttribute)
370 {
371   ObjectPtr anObject;
372   std::string anAttrType = theAttribute->attributeType();
373   if (anAttrType == ModelAPI_AttributeRefAttr::typeId()) {
374     AttributeRefAttrPtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
375     if (anAttr != NULL && anAttr->isObject())
376       anObject = anAttr->object();
377   }
378   if (anAttrType == ModelAPI_AttributeSelection::typeId()) {
379     AttributeSelectionPtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
380     if (anAttr != NULL)
381       anObject = anAttr->context();
382   }
383   if (anAttrType == ModelAPI_AttributeReference::typeId()) {
384     AttributeReferencePtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
385     if (anAttr.get() != NULL)
386       anObject = anAttr->value();
387   }
388   return anObject;
389 }
390
391 TopAbs_ShapeEnum getCompoundSubType(const TopoDS_Shape& theShape)
392 {
393   TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
394
395   // for compounds check sub-shapes: it may be compound of needed type:
396   // Booleans may produce compounds of Solids
397   if (aShapeType == TopAbs_COMPOUND) {
398     for(TopoDS_Iterator aSubs(theShape); aSubs.More(); aSubs.Next()) {
399       if (!aSubs.Value().IsNull()) {
400         TopAbs_ShapeEnum aSubType = aSubs.Value().ShapeType();
401         if (aSubType == TopAbs_COMPOUND) { // compound of compound(s)
402           aShapeType = TopAbs_COMPOUND;
403           break;
404         }
405         if (aShapeType == TopAbs_COMPOUND) {
406           aShapeType = aSubType;
407         } else if (aShapeType != aSubType) { // compound of shapes of different types
408           aShapeType = TopAbs_COMPOUND;
409           break;
410         }
411       }
412     }
413   }
414   return aShapeType;
415 }
416
417 void getParameters(QStringList& theParameters)
418 {
419   theParameters.clear();
420
421   SessionPtr aSession = ModelAPI_Session::get();
422   std::list<DocumentPtr> aDocList;
423   DocumentPtr anActiveDocument = aSession->activeDocument();
424   DocumentPtr aRootDocument = aSession->moduleDocument();
425   aDocList.push_back(anActiveDocument);
426   if (anActiveDocument != aRootDocument) {
427     aDocList.push_back(aRootDocument);
428   }
429   std::string aGroupId = ModelAPI_ResultParameter::group();
430   for(std::list<DocumentPtr>::const_iterator it = aDocList.begin(); it != aDocList.end(); ++it) {
431     DocumentPtr aDocument = *it;
432     int aSize = aDocument->size(aGroupId);
433     for (int i = 0; i < aSize; i++) {
434       ObjectPtr anObject = aDocument->object(aGroupId, i);
435       std::string aParameterName = anObject->data()->name();
436       theParameters.append(aParameterName.c_str());
437     }
438   }
439 }
440
441 std::string findGreedAttribute(ModuleBase_IWorkshop* theWorkshop, const FeaturePtr& theFeature)
442 {
443   std::string anAttributeId;
444
445   std::string aXmlCfg, aDescription;
446   theWorkshop->module()->getXMLRepresentation(theFeature->getKind(), aXmlCfg, aDescription);
447
448   ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
449   std::string anAttributeTitle;
450   aFactory.getGreedAttribute(anAttributeId);
451
452   return anAttributeId;
453 }
454
455 bool hasObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
456                const std::shared_ptr<GeomAPI_Shape>& theShape,
457                ModuleBase_IWorkshop* theWorkshop,
458                const bool theTemporarily)
459 {
460   bool aHasObject = false;
461   if (!theAttribute.get())
462     return aHasObject;
463
464   std::string aType = theAttribute->attributeType();
465   if (aType == ModelAPI_AttributeReference::typeId()) {
466     AttributeReferencePtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
467     ObjectPtr aObject = aRef->value();
468     aHasObject = aObject && aObject->isSame(theObject);
469     //if (!(aObject && aObject->isSame(theObject))) {
470     //  aRef->setValue(theObject);
471     //}
472   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
473     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
474
475     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
476     if (anAttribute.get()) {
477       //aRefAttr->setAttr(anAttribute);
478     }
479     else {
480       ObjectPtr aObject = aRefAttr->object();
481       aHasObject = aObject && aObject->isSame(theObject);
482       //if (!(aObject && aObject->isSame(theObject))) {
483       //  aRefAttr->setObject(theObject);
484       //}
485     }
486   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
487     /*AttributeSelectionPtr aSelectAttr =
488                              std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
489     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
490     if (aSelectAttr.get() != NULL) {
491       aSelectAttr->setValue(aResult, theShape, theTemporarily);
492     }*/
493   }
494   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
495     AttributeSelectionListPtr aSelectionListAttr =
496                          std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
497     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
498     aHasObject = aSelectionListAttr->isInList(aResult, theShape, theTemporarily);
499     //if (!theCheckIfAttributeHasObject || !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
500     //  aSelectionListAttr->append(aResult, theShape, theTemporarily);
501   }
502   else if (aType == ModelAPI_AttributeRefList::typeId()) {
503     AttributeRefListPtr aRefListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
504     aHasObject = aRefListAttr->isInList(theObject);
505     //if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
506     //  aRefListAttr->append(theObject);
507   }
508   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
509     AttributeRefAttrListPtr aRefAttrListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
510     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
511
512     if (anAttribute.get()) {
513       aHasObject = aRefAttrListAttr->isInList(anAttribute);
514       //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
515       //  aRefAttrListAttr->append(anAttribute);
516     }
517     else {
518       aHasObject = aRefAttrListAttr->isInList(theObject);
519       //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
520       //  aRefAttrListAttr->append(theObject);
521     }
522   }
523   return aHasObject;
524 }
525
526 void setObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
527                const GeomShapePtr& theShape, ModuleBase_IWorkshop* theWorkshop,
528                const bool theTemporarily, const bool theCheckIfAttributeHasObject)
529 {
530   if (!theAttribute.get())
531     return;
532
533   std::string aType = theAttribute->attributeType();
534   if (aType == ModelAPI_AttributeReference::typeId()) {
535     AttributeReferencePtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
536     ObjectPtr aObject = aRef->value();
537     if (!(aObject && aObject->isSame(theObject))) {
538       aRef->setValue(theObject);
539     }
540   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
541     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
542
543     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
544     if (anAttribute.get())
545       aRefAttr->setAttr(anAttribute);
546     else {
547       ObjectPtr aObject = aRefAttr->object();
548       if (!(aObject && aObject->isSame(theObject))) {
549         aRefAttr->setObject(theObject);
550       }
551     }
552   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
553     AttributeSelectionPtr aSelectAttr =
554                              std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
555     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
556     if (aSelectAttr.get() != NULL) {
557       aSelectAttr->setValue(aResult, theShape, theTemporarily);
558     }
559   }
560   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
561     AttributeSelectionListPtr aSelectionListAttr =
562                          std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
563     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
564     if (!theCheckIfAttributeHasObject || !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
565       aSelectionListAttr->append(aResult, theShape, theTemporarily);
566   }
567   else if (aType == ModelAPI_AttributeRefList::typeId()) {
568     AttributeRefListPtr aRefListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
569     if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
570       aRefListAttr->append(theObject);
571   }
572   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
573     AttributeRefAttrListPtr aRefAttrListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
574     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
575
576     if (anAttribute.get()) {
577       if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
578         aRefAttrListAttr->append(anAttribute);
579     }
580     else {
581       if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
582         aRefAttrListAttr->append(theObject);
583     }
584   }
585 }
586
587 GeomShapePtr getShape(const AttributePtr& theAttribute, ModuleBase_IWorkshop* theWorkshop)
588 {
589   GeomShapePtr aShape;
590   if (!theAttribute.get())
591     return aShape;
592
593   std::string aType = theAttribute->attributeType();
594   if (aType == ModelAPI_AttributeReference::typeId()) {
595   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
596     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
597     if (aRefAttr.get() && !aRefAttr->isObject()) {
598       AttributePtr anAttribute = aRefAttr->attr();
599       aShape = theWorkshop->module()->findShape(anAttribute);
600     }
601   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
602     AttributeSelectionPtr aSelectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>
603                                                                                  (theAttribute);
604     aShape = aSelectAttr->value();
605   }
606   return aShape;
607 }
608
609 void flushUpdated(ObjectPtr theObject)
610 {
611   blockUpdateViewer(true);
612
613   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
614
615   blockUpdateViewer(false);
616 }
617
618 void blockUpdateViewer(const bool theValue)
619 {
620   // the viewer update should be blocked in order to avoid the temporary feature content
621   // when the solver processes the feature, the redisplay message can be flushed
622   // what caused the display in the viewer preliminary states of object
623   // e.g. fillet feature, angle value change
624   std::shared_ptr<Events_Message> aMsg;
625   if (theValue) {
626     aMsg = std::shared_ptr<Events_Message>(
627         new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)));
628   }
629   else {
630     // the viewer update should be unblocked
631     aMsg = std::shared_ptr<Events_Message>(
632         new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)));
633   }
634   Events_Loop::loop()->send(aMsg);
635 }
636
637 QString wrapTextByWords(const QString& theValue, QWidget* theWidget,
638                                           int theMaxLineInPixels)
639 {
640   static QFontMetrics tfm(theWidget ? theWidget->font() : QApplication::font());
641   static qreal phi = 2.618;
642
643   QRect aBounds = tfm.boundingRect(theValue);
644   if(aBounds.width() <= theMaxLineInPixels)
645     return theValue;
646
647   qreal s = aBounds.width() * aBounds.height();
648   qreal aGoldWidth = sqrt(s*phi);
649
650   QStringList aWords = theValue.split(" ", QString::SkipEmptyParts);
651   QStringList aLines;
652   int n = aWords.count();
653   QString aLine;
654   for (int i = 0; i < n; i++) {
655     QString aLineExt = aLine + " " + aWords[i];
656     qreal anWidthNonExt = tfm.boundingRect(aLine).width();
657     qreal anWidthExt = tfm.boundingRect(aLineExt).width();
658     qreal aDeltaNonExt = fabs(anWidthNonExt-aGoldWidth);
659     qreal aDeltaExt    = fabs(anWidthExt-aGoldWidth);
660     if(aDeltaNonExt < aDeltaExt) {
661       // new line
662       aLines.append(aLine);
663       aLine = aWords[i];
664     }
665     else
666       aLine = aLineExt;
667   }
668
669   if(!aLine.isEmpty())
670     aLines.append(aLine);
671
672   QString aResult = aLines.join("\n");
673   return aResult;
674 }
675
676 //**************************************************************
677 void refsToFeatureInFeatureDocument(const ObjectPtr& theObject, std::set<FeaturePtr>& theRefFeatures)
678 {
679   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
680   if (aFeature.get()) {
681     DocumentPtr aFeatureDoc = aFeature->document();
682     // 1. find references in the current document
683     aFeatureDoc->refsToFeature(aFeature, theRefFeatures, false);
684   }
685 }
686
687
688 //**************************************************************
689 bool isSubOfComposite(const ObjectPtr& theObject)
690 {
691   bool isSub = false;
692   std::set<FeaturePtr> aRefFeatures;
693   refsToFeatureInFeatureDocument(theObject, aRefFeatures);
694   std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
695                                        aLast = aRefFeatures.end();
696   for (; anIt != aLast && !isSub; anIt++) {
697     isSub = isSubOfComposite(theObject, *anIt);
698   }
699   return isSub;
700 }
701
702 //**************************************************************
703 bool isSubOfComposite(const ObjectPtr& theObject, const FeaturePtr& theFeature)
704 {
705   bool isSub = false;
706   CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
707   if (aComposite.get()) {
708     isSub = aComposite->isSub(theObject);
709     // the recursive is possible, the parameters are sketch circle and extrusion cut. They are
710     // separated by composite sketch feature
711     if (!isSub) {
712       int aNbSubs = aComposite->numberOfSubs();
713       for (int aSub = 0; aSub < aNbSubs && !isSub; aSub++) {
714         isSub = isSubOfComposite(theObject, aComposite->subFeature(aSub));
715       }
716     }
717   }
718   return isSub;
719 }
720
721 //**************************************************************
722 bool isFeatureOfResult(const FeaturePtr& theFeature, const std::string& theGroupOfResult)
723 {
724   bool isResult = false;
725
726   if (!theFeature->data()->isValid())
727     return isResult;
728
729   ResultPtr aFirstResult = theFeature->firstResult();
730   if (!aFirstResult.get())
731     return isResult;
732
733   return aFirstResult->groupName() == theGroupOfResult;
734 }
735
736 //**************************************************************
737 bool askToDelete(const std::set<FeaturePtr> theFeatures,
738                  const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
739                  QWidget* theParent,
740                  std::set<FeaturePtr>& theReferencesToDelete)
741 {
742   std::set<FeaturePtr> aFeaturesRefsTo;
743   std::set<FeaturePtr> aFeaturesRefsToParameter;
744   std::set<FeaturePtr> aParameterFeatures;
745   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
746                                        aLast = theFeatures.end();
747   // separate features to references to parameter features and references to others
748   for (; anIt != aLast; anIt++) {
749     FeaturePtr aFeature = *anIt;
750     if (theReferences.find(aFeature) == theReferences.end())
751       continue;
752
753     std::set<FeaturePtr> aRefFeatures;
754     std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
755     std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
756     for (; aRefIt != aRefLast; aRefIt++) {
757       FeaturePtr aRefFeature = *aRefIt;
758       if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
759           aRefFeatures.find(aRefFeature) == aRefFeatures.end()) // it is not added
760         aRefFeatures.insert(aRefFeature);
761     }
762
763     if (isFeatureOfResult(aFeature, ModelAPI_ResultParameter::group())) {
764       aFeaturesRefsToParameter.insert(aRefFeatures.begin(), aRefFeatures.end());
765       aParameterFeatures.insert(aFeature);
766     }
767     else {
768       theReferencesToDelete.insert(aRefFeatures.begin(), aRefFeatures.end());
769     }
770   }
771
772   std::set<FeaturePtr> aFeaturesRefsToParameterOnly;
773   anIt = aFeaturesRefsToParameter.begin();
774   aLast = aFeaturesRefsToParameter.end();
775   // separate features to references to parameter features and references to others
776   QStringList aParamFeatureNames;
777   for (; anIt != aLast; anIt++) {
778     FeaturePtr aFeature = *anIt;
779     if (theReferencesToDelete.find(aFeature) == theReferencesToDelete.end()) {
780       aFeaturesRefsToParameterOnly.insert(aFeature);
781       aParamFeatureNames.append(aFeature->name().c_str());
782     }
783   }
784   aParamFeatureNames.sort();
785   QStringList aPartFeatureNames, anOtherFeatureNames;
786   anIt = theReferencesToDelete.begin();
787   aLast = theReferencesToDelete.end();
788   for (; anIt != aLast; anIt++) {
789     FeaturePtr aFeature = *anIt;
790     if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
791       aPartFeatureNames.append(aFeature->name().c_str());
792     else
793       anOtherFeatureNames.append(aFeature->name().c_str());
794   }
795   aPartFeatureNames.sort();
796   anOtherFeatureNames.sort();
797
798   bool aCanReplaceParameters = !aFeaturesRefsToParameterOnly.empty();
799
800   QMessageBox aMessageBox(theParent);
801   aMessageBox.setWindowTitle(QObject::tr("Delete features"));
802   aMessageBox.setIcon(QMessageBox::Warning);
803   aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
804   aMessageBox.setDefaultButton(QMessageBox::No);
805
806   QString aText;
807   QString aSep = ", ";
808   if (!aPartFeatureNames.empty())
809     aText += QString(QObject::tr("The following parts will be deleted: %1.\n")).arg(aPartFeatureNames.join(aSep));
810   if (!anOtherFeatureNames.empty())
811     aText += QString(QObject::tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n"))
812                      .arg(anOtherFeatureNames.join(aSep));
813   if (!aParamFeatureNames.empty()) {
814     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"))
815                      .arg(aParamFeatureNames.join(aSep));
816     QPushButton *aReplaceButton = aMessageBox.addButton(QObject::tr("Replace"), QMessageBox::ActionRole);
817   }
818
819   if (!aText.isEmpty()) {
820     aText += "Would you like to continue?";
821     aMessageBox.setText(aText);
822     aMessageBox.exec();
823     QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
824
825     if (aButtonRole == QMessageBox::NoRole)
826       return false;
827
828     if (aButtonRole == QMessageBox::ActionRole) {
829       foreach (FeaturePtr aObj, aParameterFeatures)
830         ModelAPI_ReplaceParameterMessage::send(aObj, 0);
831     }
832     else
833       theReferencesToDelete.insert(aFeaturesRefsToParameterOnly.begin(), aFeaturesRefsToParameterOnly.end());
834   }
835   return true;
836 }
837
838 //**************************************************************
839 void convertToFeatures(const QObjectPtrList& theObjects, std::set<FeaturePtr>& theFeatures)
840 {
841   QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
842   for(; anIt != aLast; anIt++) {
843     ObjectPtr anObject = *anIt;
844     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
845     // for parameter result, use the corresponded reature to be removed
846     if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
847       aFeature = ModelAPI_Feature::feature(anObject);
848     }
849     theFeatures.insert(aFeature);
850   }
851 }
852
853 } // namespace ModuleBase_Tools
854
855