Salome HOME
Issue #1535 crash when mirror: debug information
[modules/shaper.git] / src / ModuleBase / ModuleBase_Tools.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        ModuleBase_Tools.cpp
4 // Created:     11 July 2014
5 // Author:      Vitaly Smetannikov
6
7 #include "ModuleBase_Tools.h"
8
9 #include <ModuleBase_ParamIntSpinBox.h>
10 #include <ModuleBase_ParamSpinBox.h>
11 #include <ModuleBase_WidgetFactory.h>
12 #include <ModuleBase_IWorkshop.h>
13 #include <ModuleBase_IModule.h>
14 #include <ModuleBase_IconFactory.h>
15
16 #include <ModelAPI_Attribute.h>
17 #include <ModelAPI_AttributeRefAttr.h>
18 #include <ModelAPI_AttributeReference.h>
19 #include <ModelAPI_AttributeSelection.h>
20 #include <ModelAPI_AttributeSelectionList.h>
21 #include <ModelAPI_AttributeRefList.h>
22 #include <ModelAPI_AttributeRefAttrList.h>
23 #include <ModelAPI_ResultPart.h>
24 #include <Events_Loop.h>
25
26 #include <ModelAPI_Data.h>
27 #include <ModelAPI_Result.h>
28 #include <ModelAPI_ResultCompSolid.h>
29 #include <ModelAPI_ResultParameter.h>
30 #include <ModelAPI_Tools.h>
31 #include <ModelAPI_Session.h>
32 #include <ModelAPI_Events.h>
33
34 #include <TopoDS_Iterator.hxx>
35
36 #include <GeomDataAPI_Point2D.h>
37 #include <Events_Error.h>
38
39 #include <Config_PropManager.h>
40
41 #include <QWidget>
42 #include <QLayout>
43 #include <QPainter>
44 #include <QBitmap>
45 #include <QDoubleSpinBox>
46 #include <QGraphicsDropShadowEffect>
47 #include <QColor>
48 #include <QApplication>
49 #include <QMessageBox>
50 #include <QAction>
51
52 #include <sstream>
53 #include <string>
54
55 const double tolerance = 1e-7;
56
57 //#define DEBUG_ACTIVATE_WINDOW
58 //#define DEBUG_SET_FOCUS
59 //#define DEBUG_SELECTION_INFO
60
61 #ifdef DEBUG_SELECTION_INFO
62 #include <ModuleBase_ISelection.h>
63 #include <ModuleBase_ViewerPrs.h>
64
65 #include <AIS_InteractiveContext.hxx>
66 #include <AIS_ListOfInteractive.hxx>
67 #include <AIS_ListIteratorOfListOfInteractive.hxx>
68 #include <AIS_Shape.hxx>
69 #include <TopoDS_Shape.hxx>
70 #include <AIS_LocalContext.hxx>
71 #include <NCollection_List.hxx>
72 #include <StdSelect_BRepOwner.hxx>
73 #include <TColStd_ListOfInteger.hxx>
74 #include <TColStd_ListIteratorOfListOfInteger.hxx>
75 #endif
76
77 namespace ModuleBase_Tools {
78
79 //******************************************************************
80
81 //******************************************************************
82
83 void adjustMargins(QWidget* theWidget)
84 {
85   if(!theWidget)
86     return;
87   adjustMargins(theWidget->layout());
88 }
89
90 void adjustMargins(QLayout* theLayout)
91 {
92   if(!theLayout)
93     return;
94   theLayout->setContentsMargins(2, 5, 2, 5);
95   theLayout->setSpacing(4);
96 }
97
98 void zeroMargins(QWidget* theWidget)
99 {
100   if(!theWidget)
101     return;
102   zeroMargins(theWidget->layout());
103 }
104
105 void zeroMargins(QLayout* theLayout)
106 {
107   if(!theLayout)
108     return;
109   theLayout->setContentsMargins(0, 0, 0, 0);
110   theLayout->setSpacing(5);
111 }
112
113 void activateWindow(QWidget* theWidget, const QString& theInfo)
114 {
115   theWidget->activateWindow();
116
117 #ifdef DEBUG_ACTIVATE_WINDOW
118   qDebug(QString("activateWindow: %1").arg(theInfo).toStdString().c_str());
119 #endif
120 }
121
122 void setFocus(QWidget* theWidget, const QString& theInfo)
123 {
124   theWidget->setFocus();
125
126 #ifdef DEBUG_SET_FOCUS
127   qDebug(QString("setFocus: %1").arg(theInfo).toStdString().c_str());
128 #endif
129 }
130
131 void setShadowEffect(QWidget* theWidget, const bool isSetEffect)
132 {
133   if (isSetEffect) {
134     QGraphicsDropShadowEffect* aGlowEffect = new QGraphicsDropShadowEffect();
135     aGlowEffect->setOffset(.0);
136     aGlowEffect->setBlurRadius(10.0);
137     aGlowEffect->setColor(QColor(0, 170, 255)); // Light-blue color, #00AAFF
138     theWidget->setGraphicsEffect(aGlowEffect);
139   }
140   else {
141     QGraphicsEffect* anEffect = theWidget->graphicsEffect();
142     if(anEffect)
143       anEffect->deleteLater();
144     theWidget->setGraphicsEffect(NULL);
145   }
146 }
147
148 QPixmap composite(const QString& theAdditionalIcon, const QString& theIcon)
149 {
150   QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
151   QImage anAditional(theAdditionalIcon);
152
153   if (anIcon.isNull())
154     return QPixmap();
155
156   int anAddWidth = anAditional.width();
157   int anAddHeight = anAditional.height();
158
159   int aWidth = anIcon.width();
160   int aHeight = anIcon.height();
161
162   int aStartWidthPos = aWidth - anAddWidth - 1;
163   int aStartHeightPos = aHeight - anAddHeight - 1;
164
165   for (int i = 0; i < anAddWidth && i + aStartWidthPos < aWidth; i++)
166   {
167     for (int j = 0; j < anAddHeight && j + aStartHeightPos < aHeight; j++)
168     {
169       if (qAlpha(anAditional.pixel(i, j)) > 0)
170         anIcon.setPixel(i + aStartWidthPos, j + aStartHeightPos, anAditional.pixel(i, j));
171     }
172   }
173   return QPixmap::fromImage(anIcon);
174 }
175
176 QPixmap lighter(const QString& theIcon, const int theLighterValue)
177 {
178   QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
179   if (anIcon.isNull())
180     return QPixmap();
181
182   QImage aResult = ModuleBase_IconFactory::loadImage(theIcon);
183   for (int i = 0; i < anIcon.width(); i++)
184   {
185     for (int j = 0; j < anIcon.height(); j++)
186     {
187       QRgb anRgb = anIcon.pixel(i, j);
188       QColor aPixelColor(qRed(anRgb), qGreen(anRgb), qBlue(anRgb),
189                          qAlpha(aResult.pixel(i, j)));
190
191       QColor aLighterColor = aPixelColor.lighter(theLighterValue);
192       aResult.setPixel(i, j, qRgba(aLighterColor.red(), aLighterColor.green(),
193                                     aLighterColor.blue(), aLighterColor.alpha()));
194     }
195   }
196   return QPixmap::fromImage(aResult);
197 }
198
199 void setSpinText(ModuleBase_ParamSpinBox* theSpin, const QString& theText)
200 {
201   if (theSpin->text() == theText) 
202     return;
203   // In order to avoid extra text setting because it will
204   // reset cursor position in control
205   bool isBlocked = theSpin->blockSignals(true);
206   theSpin->setText(theText);
207   theSpin->blockSignals(isBlocked);
208 }
209
210 void setSpinValue(QDoubleSpinBox* theSpin, double theValue)
211 {
212   if (fabs(theSpin->value() - theValue) < tolerance)
213     return;
214   bool isBlocked = theSpin->blockSignals(true);
215   theSpin->setValue(theValue);
216   theSpin->blockSignals(isBlocked);
217 }
218
219 void setSpinValue(ModuleBase_ParamSpinBox* theSpin, double theValue)
220 {
221   if (fabs(theSpin->value() - theValue) < tolerance)
222     return;
223   bool isBlocked = theSpin->blockSignals(true);
224   theSpin->setValue(theValue);
225   theSpin->blockSignals(isBlocked);
226 }
227
228 void setSpinText(ModuleBase_ParamIntSpinBox* theSpin, const QString& theText)
229 {
230   // In order to avoid extra text setting because it will
231   // reset cursor position in control
232   if (theSpin->text() == theText)
233     return;
234   bool isBlocked = theSpin->blockSignals(true);
235   theSpin->setText(theText);
236   theSpin->blockSignals(isBlocked);
237 }
238
239 void setSpinValue(ModuleBase_ParamIntSpinBox* theSpin, int theValue)
240 {
241   if (theSpin->value() == theValue)
242     return;
243   bool isBlocked = theSpin->blockSignals(true);
244   theSpin->setValue(theValue);
245   theSpin->blockSignals(isBlocked);
246 }
247
248 QAction* createAction(const QIcon& theIcon, const QString& theText,
249                       QObject* theParent, const QObject* theReceiver,
250                       const char* theMember, const QString& theToolTip,
251                       const QString& theStatusTip)
252 {
253   QAction* anAction = new QAction(theIcon, theText, theParent);
254   anAction->setToolTip(theToolTip.isEmpty() ? theText : theToolTip);
255   anAction->setStatusTip(!theStatusTip.isEmpty() ? theStatusTip :
256                                                    (!theToolTip.isEmpty() ? theToolTip : theText));
257   if (theReceiver)
258     QObject::connect(anAction, SIGNAL(triggered(bool)), theReceiver, theMember);
259
260   return anAction;
261 }
262
263 QString objectInfo(const ObjectPtr& theObj, const bool isUseAttributesInfo)
264 {
265   QString aFeatureStr = "feature";
266   if (!theObj.get())
267     return aFeatureStr;
268
269   std::ostringstream aPtrStr;
270   aPtrStr << "[" << theObj.get() << "]";
271
272   ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theObj);
273   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
274   if(aRes.get()) {
275     aFeatureStr.append(QString("(result%1)").arg(aPtrStr.str().c_str()).toStdString() .c_str());
276     if (aRes->isDisabled())
277       aFeatureStr.append("[disabled]");
278     if (aRes->isConcealed())
279       aFeatureStr.append("[concealed]");
280     if (ModelAPI_Tools::hasSubResults(aRes))
281       aFeatureStr.append("[hasSubResults]");
282
283     aFeature = ModelAPI_Feature::feature(aRes);
284   }
285   else
286     aFeatureStr.append(aPtrStr.str().c_str());
287
288   if (aFeature.get()) {
289     aFeatureStr.append(QString(": %1").arg(aFeature->getKind().c_str()).toStdString().c_str());
290     if (aFeature->data()->isValid()) {
291       aFeatureStr.append(QString(", name=%1").arg(theObj->data()->name().c_str()).toStdString()
292                                                                                        .c_str());
293     }
294     if (isUseAttributesInfo) {
295       std::list<AttributePtr> anAttrs = aFeature->data()->attributes("");
296       std::list<AttributePtr>::const_iterator anIt = anAttrs.begin(), aLast = anAttrs.end();
297       QStringList aValues;
298       for(; anIt != aLast; anIt++) {
299         AttributePtr anAttr = *anIt;
300         QString aValue = "not defined";
301         std::string aType = anAttr->attributeType();
302         if (aType == GeomDataAPI_Point2D::typeId()) {
303           std::shared_ptr<GeomDataAPI_Point2D> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
304                                                                                          anAttr);
305           if (aPoint.get())
306             aValue = QString("(%1, %2)").arg(aPoint->x()).arg(aPoint->y());
307         }
308         else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
309         }
310
311         aValues.push_back(QString("%1: %2").arg(anAttr->id().c_str()).arg(aValue).toStdString().c_str());
312       }
313       if (!aValues.empty())
314         aFeatureStr.append(QString(", attributes: %1").arg(aValues.join(", ").toStdString().c_str()));
315     }
316   }
317
318   return aFeatureStr;
319 }
320
321 #ifdef DEBUG_SELECTION_INFO
322 QString getShapeTypeInfo(const int theType)
323 {
324   QString anInfo = "Undefined";
325   switch(theType) {
326     case TopAbs_COMPOUND:  anInfo = "compound"; break;
327     case TopAbs_COMPSOLID: anInfo = "compsolid"; break;
328     case TopAbs_SOLID:     anInfo = "solid"; break;
329     case TopAbs_SHELL:     anInfo = "shell"; break;
330     case TopAbs_FACE:      anInfo = "face"; break;
331     case TopAbs_WIRE:      anInfo = "wire"; break;
332     case TopAbs_EDGE:      anInfo = "edge"; break;
333     case TopAbs_VERTEX:    anInfo = "vertex"; break;
334     case TopAbs_SHAPE:     anInfo = "shape"; break;
335     default: break;
336   }
337   return anInfo;
338 }
339
340 QString getModeInfo(const int theMode)
341 {
342   QString anInfo = "Undefined";
343   switch(theMode) {
344     case 0: anInfo = "SHAPE(0)"; break;
345     case 1: anInfo = "VERTEX(1)"; break;
346     case 2: anInfo = "EDGE(2)"; break;
347     case 3: anInfo = "WIRE(3)"; break;
348     case 4: anInfo = "FACE(4)"; break;
349     case 5: anInfo = "SHELL(5)"; break;
350     case 6: anInfo = "SOLID(6)"; break;
351     case 7: anInfo = "COMPSOLID(7)"; break;
352     case 8: anInfo = "COMPOUND(8)"; break;
353     case 100: anInfo = "Sel_Mode_First(100)"; break; //SketcherPrs_Tools
354     case 101: anInfo = "Sel_Constraint(101)"; break;
355     case 102: anInfo = "Sel_Dimension_All(102)"; break;
356     case 103: anInfo = "Sel_Dimension_Line(103)"; break;
357     case 104: anInfo = "Sel_Dimension_Text(104)"; break;
358     default: break;
359   }
360   return anInfo;
361 }
362
363 QString displayedInteractiveObjects(Handle(AIS_InteractiveContext)& theContext,
364                                     const bool theShapeInfoOnly = true)
365 {
366   if (theContext.IsNull())
367     return "";
368   AIS_ListOfInteractive aListOfIO;
369   theContext->DisplayedObjects(aListOfIO, false);
370   QStringList anObjects;
371   AIS_ListIteratorOfListOfInteractive aIt;
372   for (aIt.Initialize(aListOfIO); aIt.More(); aIt.Next()) {
373     Handle(AIS_InteractiveObject) anAISIO = aIt.Value();
374     Handle(AIS_Shape) aShapePrs = Handle(AIS_Shape)::DownCast(anAISIO);
375     if (theShapeInfoOnly && aShapePrs.IsNull())
376       continue;
377
378     QString anInfo = "IO";
379     std::ostringstream aPtrStr;
380     aPtrStr << "[" << anAISIO.Access() << "]";
381     anInfo += aPtrStr.str().c_str();
382
383     if (!aShapePrs.IsNull()) {
384       const TopoDS_Shape& aShape = aShapePrs->Shape();
385       if (aShape.IsNull())
386         Events_Error::throwException("An empty AIS presentation");
387       else
388         anInfo += QString(", shape type: %1").arg(getShapeTypeInfo(aShape.ShapeType()));
389     }
390     TColStd_ListOfInteger aTColModes;
391     theContext->ActivatedModes(anAISIO, aTColModes);
392     TColStd_ListIteratorOfListOfInteger itr( aTColModes );
393     QIntList aModesActivatedForIO;
394     bool isDeactivated = false;
395     QStringList aModes;
396     for (; itr.More(); itr.Next() ) {
397       Standard_Integer aMode = itr.Value();
398       aModes.append(getModeInfo(aMode));
399       //int aShapeMode = (aMode > 8)? aMode : AIS_Shape::SelectionType(aMode);
400     }
401     if (aModes.size() > 0)
402       anInfo += QString(", activated modes: %1").arg(aModes.join(", "));
403
404     anObjects += anInfo;
405   }
406   QString aValue = QString("displayedIO[%1]").arg(anObjects.size());
407   if (anObjects.size() > 0)
408     aValue += QString(":\n  %1").arg(anObjects.join("\n  "));
409   return aValue;
410 }
411
412 QString activeOwners(Handle(AIS_InteractiveContext)& theContext, const bool theShapeInfoOnly = true)
413 {
414   if (theContext.IsNull())
415     return "";
416   Handle(AIS_LocalContext) aLContext = theContext->LocalContext();
417   TCollection_AsciiString aSelectionName = aLContext->SelectionName();
418   aLContext->UnhilightPicked(Standard_False);
419
420   NCollection_List<Handle(SelectBasics_EntityOwner)> anActiveOwners;
421   aLContext->MainSelector()->ActiveOwners(anActiveOwners);
422   NCollection_List<Handle(SelectBasics_EntityOwner)>::Iterator anOwnersIt (anActiveOwners);
423   Handle(SelectMgr_EntityOwner) anOwner;
424   QStringList anObjects;
425   for (; anOwnersIt.More(); anOwnersIt.Next()) {
426     anOwner = Handle(SelectMgr_EntityOwner)::DownCast (anOwnersIt.Value());
427     Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
428     if (theShapeInfoOnly && BROwnr.IsNull())
429       continue;
430
431     QString anInfo = "Owner";
432     std::ostringstream aPtrStr;
433     aPtrStr << "[" << anOwner.Access() << "]";
434     anInfo += aPtrStr.str().c_str();
435
436     Handle(AIS_InteractiveObject) aAISObj = 
437           Handle(AIS_InteractiveObject)::DownCast(anOwner->Selectable());
438     if (!aAISObj.IsNull()) {
439       std::ostringstream aPtrStr;
440       aPtrStr << "[" << aAISObj.Access() << "]";
441       anInfo += QString(", selectable(IO): %1").arg(aPtrStr.str().c_str());
442     }
443
444     if (!BROwnr.IsNull() && BROwnr->HasShape()) {
445       const TopoDS_Shape& aShape = BROwnr->Shape();
446       if (aShape.IsNull())
447         Events_Error::throwException("An empty AIS presentation");
448       else
449         anInfo += QString(", shape type: %1").arg(getShapeTypeInfo(aShape.ShapeType()));
450     }
451     anObjects += anInfo;
452   }
453   QString aValue = QString("activeOwners[%1]").arg(anObjects.size());
454   if (anObjects.size() > 0)
455     aValue += QString(":\n  %1").arg(anObjects.join("\n  "));
456   return aValue;
457 }
458
459 QString selectedOwners(Handle(AIS_InteractiveContext)& theContext, const bool theShapeInfoOnly = true)
460 {
461   QStringList anObjects;
462   if (theContext.IsNull())
463     return "";
464
465   QList<long> aSelectedIds; // Remember of selected address in order to avoid duplicates
466   for (theContext->InitSelected(); theContext->MoreSelected(); theContext->NextSelected()) {
467     Handle(SelectMgr_EntityOwner) anOwner = theContext->SelectedOwner();
468     Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
469     if (theShapeInfoOnly && BROwnr.IsNull())
470       continue;
471
472     if (aSelectedIds.contains((long)anOwner.Access()))
473       continue;
474     aSelectedIds.append((long)anOwner.Access());
475
476     QString anInfo = "Owner";
477     std::ostringstream aPtrStr;
478     aPtrStr << "[" << anOwner.Access() << "]";
479     anInfo += aPtrStr.str().c_str();
480
481     if (!BROwnr.IsNull() && BROwnr->HasShape()) {
482       const TopoDS_Shape& aShape = BROwnr->Shape();
483       anInfo += QString(", shape type = %1").arg(getShapeTypeInfo(aShape.ShapeType()));
484     }
485     anObjects += anInfo;
486   }
487   QString aValue = QString("selectedOwners[%1]").arg(anObjects.size());
488   if (anObjects.size() > 0)
489     aValue += QString(":\n  %1").arg(anObjects.join("\n  "));
490   return aValue;
491 }
492 #endif
493
494 void selectionInfo(Handle(AIS_InteractiveContext)& theContext, const std::string& thePrefix)
495 {
496 #ifdef DEBUG_SELECTION_INFO
497   QString aValue = QString("\n\n\nDEBUG_SELECTION_INFO for '%1'\n%2\n%3\n%4")
498                                               .arg(thePrefix.c_str())
499                                               .arg(displayedInteractiveObjects(theContext))
500                                               .arg(activeOwners(theContext))
501                                               .arg(selectedOwners(theContext));
502   qDebug(aValue.toStdString().c_str());
503 #endif
504 }
505
506 typedef QMap<QString, TopAbs_ShapeEnum> ShapeTypes;
507 static ShapeTypes myShapeTypes;
508
509 TopAbs_ShapeEnum shapeType(const QString& theType)
510 {
511   if (myShapeTypes.count() == 0) {
512     myShapeTypes["compound"]   = TopAbs_COMPOUND;
513     myShapeTypes["compounds"]  = TopAbs_COMPOUND;
514     myShapeTypes["compsolid"]  = TopAbs_COMPSOLID;
515     myShapeTypes["compsolids"] = TopAbs_COMPSOLID;
516     myShapeTypes["solid"]      = TopAbs_SOLID;
517     myShapeTypes["solids"]     = TopAbs_SOLID;
518     myShapeTypes["shell"]      = TopAbs_SHELL;
519     myShapeTypes["shells"]     = TopAbs_SHELL;
520     myShapeTypes["face"]       = TopAbs_FACE;
521     myShapeTypes["faces"]      = TopAbs_FACE;
522     myShapeTypes["wire"]       = TopAbs_WIRE;
523     myShapeTypes["wires"]      = TopAbs_WIRE;
524     myShapeTypes["edge"]       = TopAbs_EDGE;
525     myShapeTypes["edges"]      = TopAbs_EDGE;
526     myShapeTypes["vertex"]     = TopAbs_VERTEX;
527     myShapeTypes["vertices"]   = TopAbs_VERTEX;
528     myShapeTypes["objects"]    = TopAbs_SHAPE;
529   }
530   QString aType = theType.toLower();
531   if(myShapeTypes.contains(aType))
532     return myShapeTypes[aType];
533   Events_Error::send("Shape type defined in XML is not implemented!");
534   return TopAbs_SHAPE;
535 }
536
537 void checkObjects(const QObjectPtrList& theObjects, bool& hasResult, bool& hasFeature,
538                   bool& hasParameter, bool& hasCompositeOwner)
539 {
540   hasResult = false;
541   hasFeature = false;
542   hasParameter = false;
543   hasCompositeOwner = false;
544   foreach(ObjectPtr aObj, theObjects) {
545     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
546     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
547     ResultParameterPtr aConstruction = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aResult);
548
549     hasResult |= (aResult.get() != NULL);
550     hasFeature |= (aFeature.get() != NULL);
551     hasParameter |= (aConstruction.get() != NULL);
552     if (hasFeature) 
553       hasCompositeOwner |= (ModelAPI_Tools::compositeOwner(aFeature) != NULL);
554     if (hasFeature && hasResult  && hasParameter && hasCompositeOwner)
555       break;
556   }
557 }
558
559 void setDefaultDeviationCoefficient(const TopoDS_Shape& theShape,
560                                     const Handle(Prs3d_Drawer)& theDrawer)
561 {
562   if (theShape.IsNull())
563     return;
564   TopAbs_ShapeEnum aType = theShape.ShapeType();
565   if ((aType == TopAbs_EDGE) || (aType == TopAbs_WIRE)) 
566     theDrawer->SetDeviationCoefficient(1.e-4);
567 }
568
569 Quantity_Color color(const std::string& theSection,
570                      const std::string& theName,
571                      const std::string& theDefault)
572 {
573   std::vector<int> aColor = Config_PropManager::color(theSection, theName, theDefault);
574   return Quantity_Color(aColor[0] / 255., aColor[1] / 255., aColor[2] / 255., Quantity_TOC_RGB);
575 }
576
577 ObjectPtr getObject(const AttributePtr& theAttribute)
578 {
579   ObjectPtr anObject;
580   std::string anAttrType = theAttribute->attributeType();
581   if (anAttrType == ModelAPI_AttributeRefAttr::typeId()) {
582     AttributeRefAttrPtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
583     if (anAttr != NULL && anAttr->isObject())
584       anObject = anAttr->object();
585   }
586   if (anAttrType == ModelAPI_AttributeSelection::typeId()) {
587     AttributeSelectionPtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
588     if (anAttr != NULL)
589       anObject = anAttr->context();
590   }
591   if (anAttrType == ModelAPI_AttributeReference::typeId()) {
592     AttributeReferencePtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
593     if (anAttr.get() != NULL)
594       anObject = anAttr->value();
595   }
596   return anObject;
597 }
598
599 TopAbs_ShapeEnum getCompoundSubType(const TopoDS_Shape& theShape)
600 {
601   TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
602
603   // for compounds check sub-shapes: it may be compound of needed type:
604   // Booleans may produce compounds of Solids
605   if (aShapeType == TopAbs_COMPOUND) {
606     for(TopoDS_Iterator aSubs(theShape); aSubs.More(); aSubs.Next()) {
607       if (!aSubs.Value().IsNull()) {
608         TopAbs_ShapeEnum aSubType = aSubs.Value().ShapeType();
609         if (aSubType == TopAbs_COMPOUND) { // compound of compound(s)
610           aShapeType = TopAbs_COMPOUND;
611           break;
612         }
613         if (aShapeType == TopAbs_COMPOUND) {
614           aShapeType = aSubType;
615         } else if (aShapeType != aSubType) { // compound of shapes of different types
616           aShapeType = TopAbs_COMPOUND;
617           break;
618         }
619       }
620     }
621   }
622   return aShapeType;
623 }
624
625 void getParameters(QStringList& theParameters)
626 {
627   theParameters.clear();
628
629   SessionPtr aSession = ModelAPI_Session::get();
630   std::list<DocumentPtr> aDocList;
631   DocumentPtr anActiveDocument = aSession->activeDocument();
632   DocumentPtr aRootDocument = aSession->moduleDocument();
633   aDocList.push_back(anActiveDocument);
634   if (anActiveDocument != aRootDocument) {
635     aDocList.push_back(aRootDocument);
636   }
637   std::string aGroupId = ModelAPI_ResultParameter::group();
638   for(std::list<DocumentPtr>::const_iterator it = aDocList.begin(); it != aDocList.end(); ++it) {
639     DocumentPtr aDocument = *it;
640     int aSize = aDocument->size(aGroupId);
641     for (int i = 0; i < aSize; i++) {
642       ObjectPtr anObject = aDocument->object(aGroupId, i);
643       std::string aParameterName = anObject->data()->name();
644       theParameters.append(aParameterName.c_str());
645     }
646   }
647 }
648
649 std::string findGreedAttribute(ModuleBase_IWorkshop* theWorkshop, const FeaturePtr& theFeature)
650 {
651   std::string anAttributeId;
652
653   std::string aXmlCfg, aDescription;
654   theWorkshop->module()->getXMLRepresentation(theFeature->getKind(), aXmlCfg, aDescription);
655
656   ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
657   std::string anAttributeTitle;
658   aFactory.getGreedAttribute(anAttributeId);
659
660   return anAttributeId;
661 }
662
663 bool hasObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
664                const std::shared_ptr<GeomAPI_Shape>& theShape,
665                ModuleBase_IWorkshop* theWorkshop,
666                const bool theTemporarily)
667 {
668   bool aHasObject = false;
669   if (!theAttribute.get())
670     return aHasObject;
671
672   std::string aType = theAttribute->attributeType();
673   if (aType == ModelAPI_AttributeReference::typeId()) {
674     AttributeReferencePtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
675     ObjectPtr aObject = aRef->value();
676     aHasObject = aObject && aObject->isSame(theObject);
677     //if (!(aObject && aObject->isSame(theObject))) {
678     //  aRef->setValue(theObject);
679     //}
680   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
681     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
682
683     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
684     if (anAttribute.get()) {
685       //aRefAttr->setAttr(anAttribute);
686     }
687     else {
688       ObjectPtr aObject = aRefAttr->object();
689       aHasObject = aObject && aObject->isSame(theObject);
690       //if (!(aObject && aObject->isSame(theObject))) {
691       //  aRefAttr->setObject(theObject);
692       //}
693     }
694   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
695     /*AttributeSelectionPtr aSelectAttr =
696                              std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
697     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
698     if (aSelectAttr.get() != NULL) {
699       aSelectAttr->setValue(aResult, theShape, theTemporarily);
700     }*/
701   }
702   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
703     AttributeSelectionListPtr aSelectionListAttr =
704                          std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
705     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
706     aHasObject = aSelectionListAttr->isInList(aResult, theShape, theTemporarily);
707     //if (!theCheckIfAttributeHasObject || !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
708     //  aSelectionListAttr->append(aResult, theShape, theTemporarily);
709   }
710   else if (aType == ModelAPI_AttributeRefList::typeId()) {
711     AttributeRefListPtr aRefListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
712     aHasObject = aRefListAttr->isInList(theObject);
713     //if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
714     //  aRefListAttr->append(theObject);
715   }
716   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
717     AttributeRefAttrListPtr aRefAttrListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
718     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
719
720     if (anAttribute.get()) {
721       aHasObject = aRefAttrListAttr->isInList(anAttribute);
722       //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
723       //  aRefAttrListAttr->append(anAttribute);
724     }
725     else {
726       aHasObject = aRefAttrListAttr->isInList(theObject);
727       //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
728       //  aRefAttrListAttr->append(theObject);
729     }
730   }
731   return aHasObject;
732 }
733
734 void setObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
735                const GeomShapePtr& theShape, ModuleBase_IWorkshop* theWorkshop,
736                const bool theTemporarily, const bool theCheckIfAttributeHasObject)
737 {
738   if (!theAttribute.get())
739     return;
740
741   std::string aType = theAttribute->attributeType();
742   if (aType == ModelAPI_AttributeReference::typeId()) {
743     AttributeReferencePtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
744     ObjectPtr aObject = aRef->value();
745     if (!(aObject && aObject->isSame(theObject))) {
746       aRef->setValue(theObject);
747     }
748   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
749     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
750
751     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
752     if (anAttribute.get())
753       aRefAttr->setAttr(anAttribute);
754     else {
755       ObjectPtr aObject = aRefAttr->object();
756       if (!(aObject && aObject->isSame(theObject))) {
757         aRefAttr->setObject(theObject);
758       }
759     }
760   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
761     AttributeSelectionPtr aSelectAttr =
762                              std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
763     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
764     if (aSelectAttr.get() != NULL) {
765       aSelectAttr->setValue(aResult, theShape, theTemporarily);
766     }
767   }
768   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
769     AttributeSelectionListPtr aSelectionListAttr =
770                          std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
771     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
772     if (!theCheckIfAttributeHasObject || !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
773       aSelectionListAttr->append(aResult, theShape, theTemporarily);
774   }
775   else if (aType == ModelAPI_AttributeRefList::typeId()) {
776     AttributeRefListPtr aRefListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
777     if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
778       aRefListAttr->append(theObject);
779   }
780   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
781     AttributeRefAttrListPtr aRefAttrListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
782     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
783
784     if (anAttribute.get()) {
785       if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
786         aRefAttrListAttr->append(anAttribute);
787     }
788     else {
789       if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
790         aRefAttrListAttr->append(theObject);
791     }
792   }
793 }
794
795 GeomShapePtr getShape(const AttributePtr& theAttribute, ModuleBase_IWorkshop* theWorkshop)
796 {
797   GeomShapePtr aShape;
798   if (!theAttribute.get())
799     return aShape;
800
801   std::string aType = theAttribute->attributeType();
802   if (aType == ModelAPI_AttributeReference::typeId()) {
803   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
804     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
805     if (aRefAttr.get() && !aRefAttr->isObject()) {
806       AttributePtr anAttribute = aRefAttr->attr();
807       aShape = theWorkshop->module()->findShape(anAttribute);
808     }
809   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
810     AttributeSelectionPtr aSelectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>
811                                                                                  (theAttribute);
812     aShape = aSelectAttr->value();
813   }
814   return aShape;
815 }
816
817 void flushUpdated(ObjectPtr theObject)
818 {
819   blockUpdateViewer(true);
820
821   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
822
823   blockUpdateViewer(false);
824 }
825
826 void blockUpdateViewer(const bool theValue)
827 {
828   // the viewer update should be blocked in order to avoid the temporary feature content
829   // when the solver processes the feature, the redisplay message can be flushed
830   // what caused the display in the viewer preliminary states of object
831   // e.g. fillet feature, angle value change
832   std::shared_ptr<Events_Message> aMsg;
833   if (theValue) {
834     aMsg = std::shared_ptr<Events_Message>(
835         new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)));
836   }
837   else {
838     // the viewer update should be unblocked
839     aMsg = std::shared_ptr<Events_Message>(
840         new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)));
841   }
842   Events_Loop::loop()->send(aMsg);
843 }
844
845 QString wrapTextByWords(const QString& theValue, QWidget* theWidget,
846                                           int theMaxLineInPixels)
847 {
848   static QFontMetrics tfm(theWidget ? theWidget->font() : QApplication::font());
849   static qreal phi = 2.618;
850
851   QRect aBounds = tfm.boundingRect(theValue);
852   if(aBounds.width() <= theMaxLineInPixels)
853     return theValue;
854
855   qreal s = aBounds.width() * aBounds.height();
856   qreal aGoldWidth = sqrt(s*phi);
857
858   QStringList aWords = theValue.split(" ", QString::SkipEmptyParts);
859   QStringList aLines;
860   int n = aWords.count();
861   QString aLine;
862   for (int i = 0; i < n; i++) {
863     QString aLineExt = aLine + " " + aWords[i];
864     qreal anWidthNonExt = tfm.boundingRect(aLine).width();
865     qreal anWidthExt = tfm.boundingRect(aLineExt).width();
866     qreal aDeltaNonExt = fabs(anWidthNonExt-aGoldWidth);
867     qreal aDeltaExt    = fabs(anWidthExt-aGoldWidth);
868     if(aDeltaNonExt < aDeltaExt) {
869       // new line
870       aLines.append(aLine);
871       aLine = aWords[i];
872     }
873     else
874       aLine = aLineExt;
875   }
876
877   if(!aLine.isEmpty())
878     aLines.append(aLine);
879
880   QString aResult = aLines.join("\n");
881   return aResult;
882 }
883
884 //**************************************************************
885 void refsToFeatureInFeatureDocument(const ObjectPtr& theObject, std::set<FeaturePtr>& theRefFeatures)
886 {
887   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
888   if (aFeature.get()) {
889     DocumentPtr aFeatureDoc = aFeature->document();
890     // 1. find references in the current document
891     aFeatureDoc->refsToFeature(aFeature, theRefFeatures, false);
892   }
893 }
894
895
896 //**************************************************************
897 bool isSubOfComposite(const ObjectPtr& theObject)
898 {
899   bool isSub = false;
900   std::set<FeaturePtr> aRefFeatures;
901   refsToFeatureInFeatureDocument(theObject, aRefFeatures);
902   std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
903                                        aLast = aRefFeatures.end();
904   for (; anIt != aLast && !isSub; anIt++) {
905     isSub = isSubOfComposite(theObject, *anIt);
906   }
907   return isSub;
908 }
909
910 //**************************************************************
911 bool isSubOfComposite(const ObjectPtr& theObject, const FeaturePtr& theFeature)
912 {
913   bool isSub = false;
914   CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
915   if (aComposite.get()) {
916     isSub = aComposite->isSub(theObject);
917     // the recursive is possible, the parameters are sketch circle and extrusion cut. They are
918     // separated by composite sketch feature
919     if (!isSub) {
920       int aNbSubs = aComposite->numberOfSubs();
921       for (int aSub = 0; aSub < aNbSubs && !isSub; aSub++) {
922         isSub = isSubOfComposite(theObject, aComposite->subFeature(aSub));
923       }
924     }
925   }
926   return isSub;
927 }
928
929 //**************************************************************
930 bool isFeatureOfResult(const FeaturePtr& theFeature, const std::string& theGroupOfResult)
931 {
932   bool isResult = false;
933
934   if (!theFeature->data()->isValid())
935     return isResult;
936
937   ResultPtr aFirstResult = theFeature->firstResult();
938   if (!aFirstResult.get())
939     return isResult;
940
941   return aFirstResult->groupName() == theGroupOfResult;
942 }
943
944 //**************************************************************
945 bool askToDelete(const std::set<FeaturePtr> theFeatures,
946                  const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
947                  QWidget* theParent,
948                  std::set<FeaturePtr>& theReferencesToDelete)
949 {
950   std::set<FeaturePtr> aFeaturesRefsTo;
951   std::set<FeaturePtr> aFeaturesRefsToParameter;
952   std::set<FeaturePtr> aParameterFeatures;
953   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
954                                        aLast = theFeatures.end();
955   // separate features to references to parameter features and references to others
956   for (; anIt != aLast; anIt++) {
957     FeaturePtr aFeature = *anIt;
958     if (theReferences.find(aFeature) == theReferences.end())
959       continue;
960
961     std::set<FeaturePtr> aRefFeatures;
962     std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
963     std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
964     for (; aRefIt != aRefLast; aRefIt++) {
965       FeaturePtr aRefFeature = *aRefIt;
966       if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
967           aRefFeatures.find(aRefFeature) == aRefFeatures.end()) // it is not added
968         aRefFeatures.insert(aRefFeature);
969     }
970
971     if (isFeatureOfResult(aFeature, ModelAPI_ResultParameter::group())) {
972       aFeaturesRefsToParameter.insert(aRefFeatures.begin(), aRefFeatures.end());
973       aParameterFeatures.insert(aFeature);
974     }
975     else {
976       theReferencesToDelete.insert(aRefFeatures.begin(), aRefFeatures.end());
977     }
978   }
979
980   std::set<FeaturePtr> aFeaturesRefsToParameterOnly;
981   anIt = aFeaturesRefsToParameter.begin();
982   aLast = aFeaturesRefsToParameter.end();
983   // separate features to references to parameter features and references to others
984   QStringList aParamFeatureNames;
985   for (; anIt != aLast; anIt++) {
986     FeaturePtr aFeature = *anIt;
987     if (theReferencesToDelete.find(aFeature) == theReferencesToDelete.end()) {
988       aFeaturesRefsToParameterOnly.insert(aFeature);
989       aParamFeatureNames.append(aFeature->name().c_str());
990     }
991   }
992   aParamFeatureNames.sort();
993   QStringList aPartFeatureNames, anOtherFeatureNames;
994   anIt = theReferencesToDelete.begin();
995   aLast = theReferencesToDelete.end();
996   for (; anIt != aLast; anIt++) {
997     FeaturePtr aFeature = *anIt;
998     if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
999       aPartFeatureNames.append(aFeature->name().c_str());
1000     else
1001       anOtherFeatureNames.append(aFeature->name().c_str());
1002   }
1003   aPartFeatureNames.sort();
1004   anOtherFeatureNames.sort();
1005
1006   bool aCanReplaceParameters = !aFeaturesRefsToParameterOnly.empty();
1007
1008   QMessageBox aMessageBox(theParent);
1009   aMessageBox.setWindowTitle(QObject::tr("Delete features"));
1010   aMessageBox.setIcon(QMessageBox::Warning);
1011   aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1012   aMessageBox.setDefaultButton(QMessageBox::No);
1013
1014   QString aText;
1015   QString aSep = ", ";
1016   if (!aPartFeatureNames.empty())
1017     aText += QString(QObject::tr("The following parts will be deleted: %1.\n")).arg(aPartFeatureNames.join(aSep));
1018   if (!anOtherFeatureNames.empty())
1019     aText += QString(QObject::tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n"))
1020                      .arg(anOtherFeatureNames.join(aSep));
1021   if (!aParamFeatureNames.empty()) {
1022     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"))
1023                      .arg(aParamFeatureNames.join(aSep));
1024     QPushButton *aReplaceButton = aMessageBox.addButton(QObject::tr("Replace"), QMessageBox::ActionRole);
1025   }
1026
1027   if (!aText.isEmpty()) {
1028     aText += "Would you like to continue?";
1029     aMessageBox.setText(aText);
1030     aMessageBox.exec();
1031     QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1032
1033     if (aButtonRole == QMessageBox::NoRole)
1034       return false;
1035
1036     if (aButtonRole == QMessageBox::ActionRole) {
1037       foreach (FeaturePtr aObj, aParameterFeatures)
1038         ModelAPI_ReplaceParameterMessage::send(aObj, 0);
1039     }
1040     else
1041       theReferencesToDelete.insert(aFeaturesRefsToParameterOnly.begin(), aFeaturesRefsToParameterOnly.end());
1042   }
1043   return true;
1044 }
1045
1046 //**************************************************************
1047 void convertToFeatures(const QObjectPtrList& theObjects, std::set<FeaturePtr>& theFeatures)
1048 {
1049   QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1050   for(; anIt != aLast; anIt++) {
1051     ObjectPtr anObject = *anIt;
1052     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1053     // for parameter result, use the corresponded reature to be removed
1054     if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1055       aFeature = ModelAPI_Feature::feature(anObject);
1056     }
1057     theFeatures.insert(aFeature);
1058   }
1059 }
1060
1061 } // namespace ModuleBase_Tools
1062
1063