]> SALOME platform Git repositories - modules/shaper.git/blob - src/ModuleBase/ModuleBase_Tools.cpp
Salome HOME
3211a935a2c596e6a2998519435143525bef774f
[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 void findReferences(const QObjectPtrList& theList,
661                     std::set<FeaturePtr>& aDirectRefFeatures,
662                     std::set<FeaturePtr>& aIndirectRefFeatures)
663 {
664   foreach (ObjectPtr aDeletedObj, theList) {
665     std::set<FeaturePtr> alreadyProcessed;
666     refsToFeatureInAllDocuments(aDeletedObj, aDeletedObj, theList, aDirectRefFeatures,
667                                             aIndirectRefFeatures, alreadyProcessed);
668     std::set<FeaturePtr> aDifference;
669     std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(), 
670                         aDirectRefFeatures.begin(), aDirectRefFeatures.end(), 
671                         std::inserter(aDifference, aDifference.begin()));
672     aIndirectRefFeatures = aDifference;
673   }
674 }
675
676 //**************************************************************
677 void refsToFeatureInAllDocuments(const ObjectPtr& theSourceObject, const ObjectPtr& theObject,
678                                  const QObjectPtrList& theIgnoreList,
679                                  std::set<FeaturePtr>& theDirectRefFeatures, 
680                                  std::set<FeaturePtr>& theIndirectRefFeatures,
681                                  std::set<FeaturePtr>& theAlreadyProcessed)
682 {
683   refsDirectToFeatureInAllDocuments(theSourceObject, theObject, theIgnoreList, theDirectRefFeatures, 
684                                     theAlreadyProcessed);
685
686   // Run recursion. It is possible recursive dependency, like the following: plane, extrusion uses plane,
687   // axis is built on extrusion. Delete of a plane should check the dependency from the axis also.
688   std::set<FeaturePtr>::const_iterator aFeatureIt = theDirectRefFeatures.begin();
689   for (; aFeatureIt != theDirectRefFeatures.end(); ++aFeatureIt) {
690     std::set<FeaturePtr> aRecursiveRefFeatures;
691     refsToFeatureInAllDocuments(theSourceObject, *aFeatureIt, theIgnoreList,
692       aRecursiveRefFeatures, aRecursiveRefFeatures, theAlreadyProcessed);
693     theIndirectRefFeatures.insert(aRecursiveRefFeatures.begin(), aRecursiveRefFeatures.end());
694   }
695
696 }
697
698
699
700 //**************************************************************
701 void refsDirectToFeatureInAllDocuments(const ObjectPtr& theSourceObject, const ObjectPtr& theObject,
702                                        const QObjectPtrList& theIgnoreList,
703                                        std::set<FeaturePtr>& theDirectRefFeatures, 
704                                        std::set<FeaturePtr>& theAlreadyProcessed)
705 {
706   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
707   if (!aFeature.get())
708     return;
709   if (theAlreadyProcessed.find(aFeature) != theAlreadyProcessed.end())
710     return;
711   theAlreadyProcessed.insert(aFeature);
712
713   //convert ignore object list to containt sub-features if the composite feature is in the list
714   QObjectPtrList aFullIgnoreList;
715   QObjectPtrList::const_iterator anIIt = theIgnoreList.begin(), anILast = theIgnoreList.end();
716   for (; anIIt != anILast; anIIt++) {
717     aFullIgnoreList.append(*anIIt);
718     CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anIIt);
719     // if the current feature is aborted, the composite is removed and has invalid data
720     if (aComposite.get() && aComposite->data()->isValid()) {
721       int aNbSubs = aComposite->numberOfSubs();
722       for (int aSub = 0; aSub < aNbSubs; aSub++) {
723         aFullIgnoreList.append(aComposite->subFeature(aSub));
724       }
725     }
726   }
727
728   // 1. find references in the current document
729   std::set<FeaturePtr> aRefFeatures;
730   refsToFeatureInFeatureDocument(theObject, aRefFeatures);
731   std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
732                                        aLast = aRefFeatures.end();
733   for (; anIt != aLast; anIt++) {
734     // composite feature should not be deleted when the sub feature is to be deleted
735     if (!isSubOfComposite(theSourceObject, *anIt) && !aFullIgnoreList.contains(*anIt))
736       theDirectRefFeatures.insert(*anIt);
737   }
738
739   // 2. find references in all documents if the document of the feature is
740   // "PartSet". Features of this document can be used in all other documents
741   DocumentPtr aFeatureDoc = aFeature->document();
742
743   SessionPtr aMgr = ModelAPI_Session::get();
744   DocumentPtr aModuleDoc = aMgr->moduleDocument();
745   if (aFeatureDoc == aModuleDoc) {
746     // the feature and results of the feature should be found in references
747     std::list<ObjectPtr> aObjects;
748     aObjects.push_back(aFeature);
749     typedef std::list<std::shared_ptr<ModelAPI_Result> > ResultsList;
750     const ResultsList& aResults = aFeature->results();
751     ResultsList::const_iterator aRIter = aResults.begin();
752     for (; aRIter != aResults.cend(); aRIter++) {
753       ResultPtr aRes = *aRIter;
754       if (aRes.get())
755         aObjects.push_back(aRes);
756     }
757     // get all opened documents; found features in the documents;
758     // get a list of objects where a feature refers;
759     // search in these objects the deleted objects.
760     SessionPtr aMgr = ModelAPI_Session::get();
761     std::list<DocumentPtr> anOpenedDocs = aMgr->allOpenedDocuments();
762     std::list<DocumentPtr>::const_iterator anIt = anOpenedDocs.begin(),
763                                             aLast = anOpenedDocs.end();
764     std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
765     for (; anIt != aLast; anIt++) {
766       DocumentPtr aDocument = *anIt;
767       if (aDocument == aFeatureDoc)
768         continue; // this document has been already processed in 1.1
769
770       int aFeaturesCount = aDocument->size(ModelAPI_Feature::group());
771       for (int aId = 0; aId < aFeaturesCount; aId++) {
772         ObjectPtr anObject = aDocument->object(ModelAPI_Feature::group(), aId);
773         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
774         if (!aFeature.get())
775           continue;
776
777         aRefs.clear();
778         aFeature->data()->referencesToObjects(aRefs);
779         std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefs.begin();
780         bool aHasReferenceToObject = false;
781         for(; aRef != aRefs.end() && !aHasReferenceToObject; aRef++) {
782           std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
783           for(; aRefObj != aRef->second.end() && !aHasReferenceToObject; aRefObj++) {
784             std::list<ObjectPtr>::const_iterator aObjIt = aObjects.begin();
785             for(; aObjIt != aObjects.end() && !aHasReferenceToObject; aObjIt++) {
786               aHasReferenceToObject = *aObjIt == *aRefObj;
787             }
788           }
789         }
790         if (aHasReferenceToObject && !isSubOfComposite(theSourceObject, aFeature) &&
791             !theIgnoreList.contains(aFeature))
792           theDirectRefFeatures.insert(aFeature);
793       }
794     }
795   }
796 }
797
798 //**************************************************************
799 void refsToFeatureInFeatureDocument(const ObjectPtr& theObject, std::set<FeaturePtr>& theRefFeatures)
800 {
801   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
802   if (aFeature.get()) {
803     DocumentPtr aFeatureDoc = aFeature->document();
804     // 1. find references in the current document
805     aFeatureDoc->refsToFeature(aFeature, theRefFeatures, false);
806   }
807 }
808
809
810 //**************************************************************
811 bool isSubOfComposite(const ObjectPtr& theObject)
812 {
813   bool isSub = false;
814   std::set<FeaturePtr> aRefFeatures;
815   refsToFeatureInFeatureDocument(theObject, aRefFeatures);
816   std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
817                                        aLast = aRefFeatures.end();
818   for (; anIt != aLast && !isSub; anIt++) {
819     isSub = isSubOfComposite(theObject, *anIt);
820   }
821   return isSub;
822 }
823
824 //**************************************************************
825 bool isSubOfComposite(const ObjectPtr& theObject, const FeaturePtr& theFeature)
826 {
827   bool isSub = false;
828   CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
829   if (aComposite.get()) {
830     isSub = aComposite->isSub(theObject);
831     // the recursive is possible, the parameters are sketch circle and extrusion cut. They are
832     // separated by composite sketch feature
833     if (!isSub) {
834       int aNbSubs = aComposite->numberOfSubs();
835       for (int aSub = 0; aSub < aNbSubs && !isSub; aSub++) {
836         isSub = isSubOfComposite(theObject, aComposite->subFeature(aSub));
837       }
838     }
839   }
840   return isSub;
841 }
842
843
844 //**************************************************************
845 bool isDeleteFeatureWithReferences(const QObjectPtrList& theList,
846                                    const std::set<FeaturePtr>& aDirectRefFeatures,
847                                    const std::set<FeaturePtr>& aIndirectRefFeatures,
848                                    QWidget* theParent,
849                                    bool& doDeleteReferences)
850 {
851   doDeleteReferences = true;
852
853   QString aDirectNames, aIndirectNames;
854   if (!aDirectRefFeatures.empty()) {
855     QStringList aDirectRefNames;
856     foreach (const FeaturePtr& aFeature, aDirectRefFeatures)
857       aDirectRefNames.append(aFeature->name().c_str());
858     aDirectNames = aDirectRefNames.join(", ");
859
860     QStringList aIndirectRefNames;
861     foreach (const FeaturePtr& aFeature, aIndirectRefFeatures)
862       aIndirectRefNames.append(aFeature->name().c_str());
863     aIndirectNames = aIndirectRefNames.join(", ");
864   }
865
866   bool aCanReplaceParameters = !aDirectRefFeatures.empty();
867   QStringList aPartFeatureNames;
868   foreach (ObjectPtr aObj, theList) {
869     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
870     // invalid feature data means that the feature is already removed in model,
871     // we needn't process it. E.g. delete of feature from create operation. The operation abort
872     // will delete the operation
873     if (!aFeature->data()->isValid())
874       continue;
875     ResultPtr aFirstResult = aFeature->firstResult();
876     if (!aFirstResult.get())
877       continue;
878     std::string aResultGroupName = aFirstResult->groupName();
879     if (aResultGroupName == ModelAPI_ResultPart::group())
880       aPartFeatureNames.append(aFeature->name().c_str());
881
882     if (aCanReplaceParameters && aResultGroupName != ModelAPI_ResultParameter::group())
883       aCanReplaceParameters = false;
884   }
885   QString aPartNames = aPartFeatureNames.join(", ");
886
887   QMessageBox aMessageBox(theParent);
888   aMessageBox.setWindowTitle(QObject::tr("Delete features"));
889   aMessageBox.setIcon(QMessageBox::Warning);
890   aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
891   aMessageBox.setDefaultButton(QMessageBox::No);
892
893   QString aText;
894   if (!aDirectNames.isEmpty() || !aIndirectNames.isEmpty()) {
895     if (aCanReplaceParameters) {
896       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")
897                       .arg(aDirectNames));
898       if (!aIndirectNames.isEmpty())
899         aText += QString(QObject::tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames);
900       QPushButton *aReplaceButton = aMessageBox.addButton(QObject::tr("Replace"), QMessageBox::ActionRole);
901     } else {
902       aText = QString(QObject::tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n")).arg(aDirectNames);
903       if (!aIndirectNames.isEmpty())
904         aText += QString(QObject::tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames);
905     }
906   }
907   if (!aPartNames.isEmpty())
908     aText += QString(QObject::tr("The following parts will be deleted: %1.\n")).arg(aPartNames);
909
910   if (!aText.isEmpty()) {
911     aText += "Would you like to continue?";
912     aMessageBox.setText(aText);
913     aMessageBox.exec();
914     QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
915
916     if (aButtonRole == QMessageBox::NoRole)
917       return false;
918
919     if (aButtonRole == QMessageBox::ActionRole) {
920       foreach (ObjectPtr aObj, theList)
921         ModelAPI_ReplaceParameterMessage::send(aObj, 0);
922       doDeleteReferences = false;
923     }
924   }
925   return true;
926 }
927
928 } // namespace ModuleBase_Tools
929
930