Salome HOME
Update SketchPlugin_Projection feature (issue #1459)
[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 void setObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
440                const GeomShapePtr& theShape, ModuleBase_IWorkshop* theWorkshop,
441                const bool theTemporarily)
442 {
443   if (!theAttribute.get())
444     return;
445
446   std::string aType = theAttribute->attributeType();
447   if (aType == ModelAPI_AttributeReference::typeId()) {
448     AttributeReferencePtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
449     ObjectPtr aObject = aRef->value();
450     if (!(aObject && aObject->isSame(theObject))) {
451       aRef->setValue(theObject);
452     }
453   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
454     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
455
456     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
457     if (anAttribute.get())
458       aRefAttr->setAttr(anAttribute);
459     else {
460       ObjectPtr aObject = aRefAttr->object();
461       if (!(aObject && aObject->isSame(theObject))) {
462         aRefAttr->setObject(theObject);
463       }
464     }
465   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
466     AttributeSelectionPtr aSelectAttr =
467                              std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
468     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
469     if (aSelectAttr.get() != NULL) {
470       aSelectAttr->setValue(aResult, theShape, theTemporarily);
471     }
472   }
473   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
474     AttributeSelectionListPtr aSelectionListAttr =
475                          std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
476     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
477     if (!aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
478       aSelectionListAttr->append(aResult, theShape, theTemporarily);
479   }
480   else if (aType == ModelAPI_AttributeRefList::typeId()) {
481     AttributeRefListPtr aRefListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
482     if (!aRefListAttr->isInList(theObject))
483       aRefListAttr->append(theObject);
484   }
485   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
486     AttributeRefAttrListPtr aRefAttrListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
487     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
488
489     if (anAttribute.get()) {
490       if (!aRefAttrListAttr->isInList(anAttribute))
491         aRefAttrListAttr->append(anAttribute);
492     }
493     else {
494       if (!aRefAttrListAttr->isInList(theObject))
495         aRefAttrListAttr->append(theObject);
496     }
497   }
498 }
499
500 GeomShapePtr getShape(const AttributePtr& theAttribute, ModuleBase_IWorkshop* theWorkshop)
501 {
502   GeomShapePtr aShape;
503   if (!theAttribute.get())
504     return aShape;
505
506   std::string aType = theAttribute->attributeType();
507   if (aType == ModelAPI_AttributeReference::typeId()) {
508   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
509     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
510     if (aRefAttr.get() && !aRefAttr->isObject()) {
511       AttributePtr anAttribute = aRefAttr->attr();
512       aShape = theWorkshop->module()->findShape(anAttribute);
513     }
514   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
515     AttributeSelectionPtr aSelectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>
516                                                                                  (theAttribute);
517     aShape = aSelectAttr->value();
518   }
519   return aShape;
520 }
521
522 void flushUpdated(ObjectPtr theObject)
523 {
524   blockUpdateViewer(true);
525
526   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
527
528   blockUpdateViewer(false);
529 }
530
531 void blockUpdateViewer(const bool theValue)
532 {
533   // the viewer update should be blocked in order to avoid the temporary feature content
534   // when the solver processes the feature, the redisplay message can be flushed
535   // what caused the display in the viewer preliminary states of object
536   // e.g. fillet feature, angle value change
537   std::shared_ptr<Events_Message> aMsg;
538   if (theValue) {
539     aMsg = std::shared_ptr<Events_Message>(
540         new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)));
541   }
542   else {
543     // the viewer update should be unblocked
544     aMsg = std::shared_ptr<Events_Message>(
545         new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)));
546   }
547   Events_Loop::loop()->send(aMsg);
548 }
549
550 QString wrapTextByWords(const QString& theValue, QWidget* theWidget,
551                                           int theMaxLineInPixels)
552 {
553   static QFontMetrics tfm(theWidget ? theWidget->font() : QApplication::font());
554   static qreal phi = 2.618;
555
556   QRect aBounds = tfm.boundingRect(theValue);
557   if(aBounds.width() <= theMaxLineInPixels)
558     return theValue;
559
560   qreal s = aBounds.width() * aBounds.height();
561   qreal aGoldWidth = sqrt(s*phi);
562
563   QStringList aWords = theValue.split(" ", QString::SkipEmptyParts);
564   QStringList aLines;
565   int n = aWords.count();
566   QString aLine;
567   for (int i = 0; i < n; i++) {
568     QString aLineExt = aLine + " " + aWords[i];
569     qreal anWidthNonExt = tfm.boundingRect(aLine).width();
570     qreal anWidthExt = tfm.boundingRect(aLineExt).width();
571     qreal aDeltaNonExt = fabs(anWidthNonExt-aGoldWidth);
572     qreal aDeltaExt    = fabs(anWidthExt-aGoldWidth);
573     if(aDeltaNonExt < aDeltaExt) {
574       // new line
575       aLines.append(aLine);
576       aLine = aWords[i];
577     }
578     else
579       aLine = aLineExt;
580   }
581
582   if(!aLine.isEmpty())
583     aLines.append(aLine);
584
585   QString aResult = aLines.join("\n");
586   return aResult;
587 }
588
589 void findReferences(const QObjectPtrList& theList,
590                     std::set<FeaturePtr>& aDirectRefFeatures,
591                     std::set<FeaturePtr>& aIndirectRefFeatures)
592 {
593   foreach (ObjectPtr aDeletedObj, theList) {
594     std::set<FeaturePtr> alreadyProcessed;
595     refsToFeatureInAllDocuments(aDeletedObj, aDeletedObj, theList, aDirectRefFeatures,
596                                             aIndirectRefFeatures, alreadyProcessed);
597     std::set<FeaturePtr> aDifference;
598     std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(), 
599                         aDirectRefFeatures.begin(), aDirectRefFeatures.end(), 
600                         std::inserter(aDifference, aDifference.begin()));
601     aIndirectRefFeatures = aDifference;
602   }
603 }
604
605 //**************************************************************
606 void refsToFeatureInAllDocuments(const ObjectPtr& theSourceObject, const ObjectPtr& theObject,
607                                  const QObjectPtrList& theIgnoreList,
608                                  std::set<FeaturePtr>& theDirectRefFeatures, 
609                                  std::set<FeaturePtr>& theIndirectRefFeatures,
610                                  std::set<FeaturePtr>& theAlreadyProcessed)
611 {
612   refsDirectToFeatureInAllDocuments(theSourceObject, theObject, theIgnoreList, theDirectRefFeatures, 
613                                     theAlreadyProcessed);
614
615   // Run recursion. It is possible recursive dependency, like the following: plane, extrusion uses plane,
616   // axis is built on extrusion. Delete of a plane should check the dependency from the axis also.
617   std::set<FeaturePtr>::const_iterator aFeatureIt = theDirectRefFeatures.begin();
618   for (; aFeatureIt != theDirectRefFeatures.end(); ++aFeatureIt) {
619     std::set<FeaturePtr> aRecursiveRefFeatures;
620     refsToFeatureInAllDocuments(theSourceObject, *aFeatureIt, theIgnoreList,
621       aRecursiveRefFeatures, aRecursiveRefFeatures, theAlreadyProcessed);
622     theIndirectRefFeatures.insert(aRecursiveRefFeatures.begin(), aRecursiveRefFeatures.end());
623   }
624
625 }
626
627
628
629 //**************************************************************
630 void refsDirectToFeatureInAllDocuments(const ObjectPtr& theSourceObject, const ObjectPtr& theObject,
631                                        const QObjectPtrList& theIgnoreList,
632                                        std::set<FeaturePtr>& theDirectRefFeatures, 
633                                        std::set<FeaturePtr>& theAlreadyProcessed)
634 {
635   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
636   if (!aFeature.get())
637     return;
638   if (theAlreadyProcessed.find(aFeature) != theAlreadyProcessed.end())
639     return;
640   theAlreadyProcessed.insert(aFeature);
641
642   //convert ignore object list to containt sub-features if the composite feature is in the list
643   QObjectPtrList aFullIgnoreList;
644   QObjectPtrList::const_iterator anIIt = theIgnoreList.begin(), anILast = theIgnoreList.end();
645   for (; anIIt != anILast; anIIt++) {
646     aFullIgnoreList.append(*anIIt);
647     CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anIIt);
648     // if the current feature is aborted, the composite is removed and has invalid data
649     if (aComposite.get() && aComposite->data()->isValid()) {
650       int aNbSubs = aComposite->numberOfSubs();
651       for (int aSub = 0; aSub < aNbSubs; aSub++) {
652         aFullIgnoreList.append(aComposite->subFeature(aSub));
653       }
654     }
655   }
656
657   // 1. find references in the current document
658   std::set<FeaturePtr> aRefFeatures;
659   refsToFeatureInFeatureDocument(theObject, aRefFeatures);
660   std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
661                                        aLast = aRefFeatures.end();
662   for (; anIt != aLast; anIt++) {
663     // composite feature should not be deleted when the sub feature is to be deleted
664     if (!isSubOfComposite(theSourceObject, *anIt) && !aFullIgnoreList.contains(*anIt))
665       theDirectRefFeatures.insert(*anIt);
666   }
667
668   // 2. find references in all documents if the document of the feature is
669   // "PartSet". Features of this document can be used in all other documents
670   DocumentPtr aFeatureDoc = aFeature->document();
671
672   SessionPtr aMgr = ModelAPI_Session::get();
673   DocumentPtr aModuleDoc = aMgr->moduleDocument();
674   if (aFeatureDoc == aModuleDoc) {
675     // the feature and results of the feature should be found in references
676     std::list<ObjectPtr> aObjects;
677     aObjects.push_back(aFeature);
678     typedef std::list<std::shared_ptr<ModelAPI_Result> > ResultsList;
679     const ResultsList& aResults = aFeature->results();
680     ResultsList::const_iterator aRIter = aResults.begin();
681     for (; aRIter != aResults.cend(); aRIter++) {
682       ResultPtr aRes = *aRIter;
683       if (aRes.get())
684         aObjects.push_back(aRes);
685     }
686     // get all opened documents; found features in the documents;
687     // get a list of objects where a feature refers;
688     // search in these objects the deleted objects.
689     SessionPtr aMgr = ModelAPI_Session::get();
690     std::list<DocumentPtr> anOpenedDocs = aMgr->allOpenedDocuments();
691     std::list<DocumentPtr>::const_iterator anIt = anOpenedDocs.begin(),
692                                             aLast = anOpenedDocs.end();
693     std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
694     for (; anIt != aLast; anIt++) {
695       DocumentPtr aDocument = *anIt;
696       if (aDocument == aFeatureDoc)
697         continue; // this document has been already processed in 1.1
698
699       int aFeaturesCount = aDocument->size(ModelAPI_Feature::group());
700       for (int aId = 0; aId < aFeaturesCount; aId++) {
701         ObjectPtr anObject = aDocument->object(ModelAPI_Feature::group(), aId);
702         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
703         if (!aFeature.get())
704           continue;
705
706         aRefs.clear();
707         aFeature->data()->referencesToObjects(aRefs);
708         std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefs.begin();
709         bool aHasReferenceToObject = false;
710         for(; aRef != aRefs.end() && !aHasReferenceToObject; aRef++) {
711           std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
712           for(; aRefObj != aRef->second.end() && !aHasReferenceToObject; aRefObj++) {
713             std::list<ObjectPtr>::const_iterator aObjIt = aObjects.begin();
714             for(; aObjIt != aObjects.end() && !aHasReferenceToObject; aObjIt++) {
715               aHasReferenceToObject = *aObjIt == *aRefObj;
716             }
717           }
718         }
719         if (aHasReferenceToObject && !isSubOfComposite(theSourceObject, aFeature) &&
720             !theIgnoreList.contains(aFeature))
721           theDirectRefFeatures.insert(aFeature);
722       }
723     }
724   }
725 }
726
727 //**************************************************************
728 void refsToFeatureInFeatureDocument(const ObjectPtr& theObject, std::set<FeaturePtr>& theRefFeatures)
729 {
730   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
731   if (aFeature.get()) {
732     DocumentPtr aFeatureDoc = aFeature->document();
733     // 1. find references in the current document
734     aFeatureDoc->refsToFeature(aFeature, theRefFeatures, false);
735   }
736 }
737
738
739 //**************************************************************
740 bool isSubOfComposite(const ObjectPtr& theObject)
741 {
742   bool isSub = false;
743   std::set<FeaturePtr> aRefFeatures;
744   refsToFeatureInFeatureDocument(theObject, aRefFeatures);
745   std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
746                                        aLast = aRefFeatures.end();
747   for (; anIt != aLast && !isSub; anIt++) {
748     isSub = isSubOfComposite(theObject, *anIt);
749   }
750   return isSub;
751 }
752
753 //**************************************************************
754 bool isSubOfComposite(const ObjectPtr& theObject, const FeaturePtr& theFeature)
755 {
756   bool isSub = false;
757   CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
758   if (aComposite.get()) {
759     isSub = aComposite->isSub(theObject);
760     // the recursive is possible, the parameters are sketch circle and extrusion cut. They are
761     // separated by composite sketch feature
762     if (!isSub) {
763       int aNbSubs = aComposite->numberOfSubs();
764       for (int aSub = 0; aSub < aNbSubs && !isSub; aSub++) {
765         isSub = isSubOfComposite(theObject, aComposite->subFeature(aSub));
766       }
767     }
768   }
769   return isSub;
770 }
771
772
773 //**************************************************************
774 bool isDeleteFeatureWithReferences(const QObjectPtrList& theList,
775                                    const std::set<FeaturePtr>& aDirectRefFeatures,
776                                    const std::set<FeaturePtr>& aIndirectRefFeatures,
777                                    QWidget* theParent,
778                                    bool& doDeleteReferences)
779 {
780   doDeleteReferences = true;
781
782   QString aDirectNames, aIndirectNames;
783   if (!aDirectRefFeatures.empty()) {
784     QStringList aDirectRefNames;
785     foreach (const FeaturePtr& aFeature, aDirectRefFeatures)
786       aDirectRefNames.append(aFeature->name().c_str());
787     aDirectNames = aDirectRefNames.join(", ");
788
789     QStringList aIndirectRefNames;
790     foreach (const FeaturePtr& aFeature, aIndirectRefFeatures)
791       aIndirectRefNames.append(aFeature->name().c_str());
792     aIndirectNames = aIndirectRefNames.join(", ");
793   }
794
795   bool aCanReplaceParameters = !aDirectRefFeatures.empty();
796   QStringList aPartFeatureNames;
797   foreach (ObjectPtr aObj, theList) {
798     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
799     // invalid feature data means that the feature is already removed in model,
800     // we needn't process it. E.g. delete of feature from create operation. The operation abort
801     // will delete the operation
802     if (!aFeature->data()->isValid())
803       continue;
804     ResultPtr aFirstResult = aFeature->firstResult();
805     if (!aFirstResult.get())
806       continue;
807     std::string aResultGroupName = aFirstResult->groupName();
808     if (aResultGroupName == ModelAPI_ResultPart::group())
809       aPartFeatureNames.append(aFeature->name().c_str());
810
811     if (aCanReplaceParameters && aResultGroupName != ModelAPI_ResultParameter::group())
812       aCanReplaceParameters = false;
813   }
814   QString aPartNames = aPartFeatureNames.join(", ");
815
816   QMessageBox aMessageBox(theParent);
817   aMessageBox.setWindowTitle(QObject::tr("Delete features"));
818   aMessageBox.setIcon(QMessageBox::Warning);
819   aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
820   aMessageBox.setDefaultButton(QMessageBox::No);
821
822   QString aText;
823   if (!aDirectNames.isEmpty() || !aIndirectNames.isEmpty()) {
824     if (aCanReplaceParameters) {
825       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")
826                       .arg(aDirectNames));
827       if (!aIndirectNames.isEmpty())
828         aText += QString(QObject::tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames);
829       QPushButton *aReplaceButton = aMessageBox.addButton(QObject::tr("Replace"), QMessageBox::ActionRole);
830     } else {
831       aText = QString(QObject::tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n")).arg(aDirectNames);
832       if (!aIndirectNames.isEmpty())
833         aText += QString(QObject::tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames);
834     }
835   }
836   if (!aPartNames.isEmpty())
837     aText += QString(QObject::tr("The following parts will be deleted: %1.\n")).arg(aPartNames);
838
839   if (!aText.isEmpty()) {
840     aText += "Would you like to continue?";
841     aMessageBox.setText(aText);
842     aMessageBox.exec();
843     QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
844
845     if (aButtonRole == QMessageBox::NoRole)
846       return false;
847
848     if (aButtonRole == QMessageBox::ActionRole) {
849       foreach (ObjectPtr aObj, theList)
850         ModelAPI_ReplaceParameterMessage::send(aObj, 0);
851       doDeleteReferences = false;
852     }
853   }
854   return true;
855 }
856
857 } // namespace ModuleBase_Tools
858
859