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