Salome HOME
250cff9ff5bbccb90ac0b7fc3f661d217c4e1933
[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
15 #include <ModelAPI_Attribute.h>
16 #include <ModelAPI_AttributeRefAttr.h>
17 #include <ModelAPI_AttributeReference.h>
18 #include <ModelAPI_AttributeSelection.h>
19 #include <ModelAPI_AttributeSelectionList.h>
20 #include <ModelAPI_AttributeRefList.h>
21 #include <ModelAPI_AttributeRefAttrList.h>
22
23 #include <ModelAPI_Data.h>
24 #include <ModelAPI_Result.h>
25 #include <ModelAPI_ResultCompSolid.h>
26 #include <ModelAPI_ResultParameter.h>
27 #include <ModelAPI_Tools.h>
28 #include <ModelAPI_Session.h>
29
30 #include <TopoDS_Iterator.hxx>
31
32 #include <GeomDataAPI_Point2D.h>
33 #include <Events_Error.h>
34
35 #include <Config_PropManager.h>
36
37 #include <QWidget>
38 #include <QLayout>
39 #include <QPainter>
40 #include <QBitmap>
41 #include <QDoubleSpinBox>
42 #include <QGraphicsDropShadowEffect>
43 #include <QColor>
44
45 #include <sstream>
46 #include <string>
47
48 const double tolerance = 1e-7;
49
50 //#define DEBUG_ACTIVATE_WINDOW
51 //#define DEBUG_SET_FOCUS
52
53 namespace ModuleBase_Tools {
54
55 //******************************************************************
56
57 //******************************************************************
58
59 void adjustMargins(QWidget* theWidget)
60 {
61   if(!theWidget)
62     return;
63   adjustMargins(theWidget->layout());
64 }
65
66 void adjustMargins(QLayout* theLayout)
67 {
68   if(!theLayout)
69     return;
70   theLayout->setContentsMargins(2, 5, 2, 5);
71   theLayout->setSpacing(4);
72 }
73
74 void zeroMargins(QWidget* theWidget)
75 {
76   if(!theWidget)
77     return;
78   zeroMargins(theWidget->layout());
79 }
80
81 void zeroMargins(QLayout* theLayout)
82 {
83   if(!theLayout)
84     return;
85   theLayout->setContentsMargins(0, 0, 0, 0);
86   theLayout->setSpacing(5);
87 }
88
89 void activateWindow(QWidget* theWidget, const QString& theInfo)
90 {
91   theWidget->activateWindow();
92
93 #ifdef DEBUG_ACTIVATE_WINDOW
94   qDebug(QString("activateWindow: %1").arg(theInfo).toStdString().c_str());
95 #endif
96 }
97
98 void setFocus(QWidget* theWidget, const QString& theInfo)
99 {
100   theWidget->setFocus();
101
102 #ifdef DEBUG_SET_FOCUS
103   qDebug(QString("setFocus: %1").arg(theInfo).toStdString().c_str());
104 #endif
105 }
106
107 void setShadowEffect(QWidget* theWidget, const bool isSetEffect)
108 {
109   if (isSetEffect) {
110     QGraphicsDropShadowEffect* aGlowEffect = new QGraphicsDropShadowEffect();
111     aGlowEffect->setOffset(.0);
112     aGlowEffect->setBlurRadius(10.0);
113     aGlowEffect->setColor(QColor(0, 170, 255)); // Light-blue color, #00AAFF
114     theWidget->setGraphicsEffect(aGlowEffect);
115   }
116   else {
117     QGraphicsEffect* anEffect = theWidget->graphicsEffect();
118     if(anEffect)
119     anEffect->deleteLater();
120     theWidget->setGraphicsEffect(NULL);
121   }
122 }
123
124 QPixmap composite(const QString& theAdditionalIcon, const QString& theIcon)
125 {
126   QImage anIcon(theIcon);
127   QImage anAditional(theAdditionalIcon);
128
129   if (anIcon.isNull())
130     return QPixmap();
131
132   int anAddWidth = anAditional.width();
133   int anAddHeight = anAditional.height();
134
135   int aWidth = anIcon.width();
136   int aHeight = anIcon.height();
137
138   int aStartWidthPos = aWidth - anAddWidth - 1;
139   int aStartHeightPos = aHeight - anAddHeight - 1;
140
141   for (int i = 0; i < anAddWidth && i + aStartWidthPos < aWidth; i++)
142   {
143     for (int j = 0; j < anAddHeight && j + aStartHeightPos < aHeight; j++)
144     {
145       if (qAlpha(anAditional.pixel(i, j)) > 0)
146         anIcon.setPixel(i + aStartWidthPos, j + aStartHeightPos, anAditional.pixel(i, j));
147     }
148   }
149   return QPixmap::fromImage(anIcon);
150 }
151
152 QPixmap lighter(const QString& theIcon, const int theLighterValue)
153 {
154   QImage anIcon(theIcon);
155   if (anIcon.isNull())
156     return QPixmap();
157
158   QImage aResult(theIcon);
159   for ( int i = 0; i < anIcon.width(); i++ )
160   {
161     for ( int j = 0; j < anIcon.height(); j++ )
162     {
163       QRgb anRgb = anIcon.pixel( i, j );
164       QColor aPixelColor(qRed(anRgb), qGreen(anRgb), qBlue(anRgb),
165                          qAlpha( aResult.pixel( i, j ) ));
166
167       QColor aLighterColor = aPixelColor.lighter(theLighterValue);
168       aResult.setPixel(i, j, qRgba( aLighterColor.red(), aLighterColor.green(),
169                                     aLighterColor.blue(), aLighterColor.alpha() ) );
170     }
171   }
172   return QPixmap::fromImage(aResult);
173 }
174
175 void setSpinText(ModuleBase_ParamSpinBox* theSpin, const QString& theText)
176 {
177   if (theSpin->text() == theText) 
178     return;
179   // In order to avoid extra text setting because it will
180   // reset cursor position in control
181   bool isBlocked = theSpin->blockSignals(true);
182   theSpin->setText(theText);
183   theSpin->blockSignals(isBlocked);
184 }
185
186 void setSpinValue(QDoubleSpinBox* theSpin, double theValue)
187 {
188   if (fabs(theSpin->value() - theValue) < tolerance)
189     return;
190   bool isBlocked = theSpin->blockSignals(true);
191   theSpin->setValue(theValue);
192   theSpin->blockSignals(isBlocked);
193 }
194
195 void setSpinValue(ModuleBase_ParamSpinBox* theSpin, double theValue)
196 {
197   if (fabs(theSpin->value() - theValue) < tolerance)
198     return;
199   bool isBlocked = theSpin->blockSignals(true);
200   theSpin->setValue(theValue);
201   theSpin->blockSignals(isBlocked);
202 }
203
204 void setSpinText(ModuleBase_ParamIntSpinBox* theSpin, const QString& theText)
205 {
206   // In order to avoid extra text setting because it will
207   // reset cursor position in control
208   if (theSpin->text() == theText)
209     return;
210   bool isBlocked = theSpin->blockSignals(true);
211   theSpin->setText(theText);
212   theSpin->blockSignals(isBlocked);
213 }
214
215 void setSpinValue(ModuleBase_ParamIntSpinBox* theSpin, int theValue)
216 {
217   if (theSpin->value() == theValue)
218     return;
219   bool isBlocked = theSpin->blockSignals(true);
220   theSpin->setValue(theValue);
221   theSpin->blockSignals(isBlocked);
222 }
223
224 QString objectInfo(const ObjectPtr& theObj, const bool isUseAttributesInfo)
225 {
226   QString aFeatureStr = "feature";
227   if (!theObj.get())
228     return aFeatureStr;
229
230   std::ostringstream aPtrStr;
231   aPtrStr << "[" << theObj.get() << "]";
232
233   ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theObj);
234   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
235   if(aRes.get()) {
236     aFeatureStr.append(QString("(result%1)").arg(aPtrStr.str().c_str()).toStdString() .c_str());
237     if (aRes->isDisabled())
238       aFeatureStr.append("[disabled]");
239     if (aRes->isConcealed())
240       aFeatureStr.append("[concealed]");
241     if (ModelAPI_Tools::hasSubResults(aRes))
242       aFeatureStr.append("[hasSubResults]");
243
244     aFeature = ModelAPI_Feature::feature(aRes);
245   }
246   else
247     aFeatureStr.append(aPtrStr.str().c_str());
248
249   if (aFeature.get()) {
250     aFeatureStr.append(QString(": %1").arg(aFeature->getKind().c_str()).toStdString().c_str());
251     if (aFeature->data()->isValid()) {
252       aFeatureStr.append(QString(", name=%1").arg(aFeature->data()->name().c_str()).toStdString()
253                                                                                        .c_str());
254     }
255     if (isUseAttributesInfo) {
256       std::list<AttributePtr> anAttrs = aFeature->data()->attributes("");
257       std::list<AttributePtr>::const_iterator anIt = anAttrs.begin(), aLast = anAttrs.end();
258       QStringList aValues;
259       for(; anIt != aLast; anIt++) {
260         AttributePtr anAttr = *anIt;
261         QString aValue = "not defined";
262         std::string aType = anAttr->attributeType();
263         if (aType == GeomDataAPI_Point2D::typeId()) {
264           std::shared_ptr<GeomDataAPI_Point2D> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
265                                                                                          anAttr);
266           if (aPoint.get())
267             aValue = QString("(%1, %2)").arg(aPoint->x()).arg(aPoint->y());
268         }
269         else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
270         }
271
272         aValues.push_back(QString("%1: %2").arg(anAttr->id().c_str()).arg(aValue).toStdString().c_str());
273       }
274       if (!aValues.empty())
275         aFeatureStr.append(QString(", attributes: %1").arg(aValues.join(", ").toStdString().c_str()));
276     }
277   }
278
279   return aFeatureStr;
280 }
281
282 typedef QMap<QString, TopAbs_ShapeEnum> ShapeTypes;
283 static ShapeTypes MyShapeTypes;
284
285 TopAbs_ShapeEnum shapeType(const QString& theType)
286 {
287   if (MyShapeTypes.count() == 0) {
288     MyShapeTypes["face"] = TopAbs_FACE;
289     MyShapeTypes["faces"] = TopAbs_FACE;
290     MyShapeTypes["vertex"] = TopAbs_VERTEX;
291     MyShapeTypes["vertices"] = TopAbs_VERTEX;
292     MyShapeTypes["wire"] = TopAbs_WIRE;
293     MyShapeTypes["edge"] = TopAbs_EDGE;
294     MyShapeTypes["edges"] = TopAbs_EDGE;
295     MyShapeTypes["shell"] = TopAbs_SHELL;
296     MyShapeTypes["solid"] = TopAbs_SOLID;
297     MyShapeTypes["solids"] = TopAbs_SOLID;
298     MyShapeTypes["objects"] = TopAbs_SHAPE;
299   }
300   QString aType = theType.toLower();
301   if (MyShapeTypes.contains(aType))
302     return MyShapeTypes[aType];
303   Events_Error::send("Shape type defined in XML is not implemented!");
304   return TopAbs_SHAPE;
305 }
306
307 void checkObjects(const QObjectPtrList& theObjects, bool& hasResult, bool& hasFeature, bool& hasParameter, bool& hasSubFeature)
308 {
309   hasResult = false;
310   hasFeature = false;
311   hasParameter = false;
312   hasSubFeature = false;
313   foreach(ObjectPtr aObj, theObjects) {
314     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
315     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
316     ResultParameterPtr aConstruction = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aResult);
317
318     hasResult |= (aResult.get() != NULL);
319     hasFeature |= (aFeature.get() != NULL);
320     hasParameter |= (aConstruction.get() != NULL);
321     if (hasFeature) 
322       hasSubFeature |= (ModelAPI_Tools::compositeOwner(aFeature) != NULL);
323     if (hasFeature && hasResult  && hasParameter && hasSubFeature)
324       break;
325   }
326 }
327
328 void setDefaultDeviationCoefficient(const TopoDS_Shape& theShape,
329                                     const Handle(Prs3d_Drawer)& theDrawer)
330 {
331   if (theShape.IsNull())
332     return;
333   TopAbs_ShapeEnum aType = theShape.ShapeType();
334   if ((aType == TopAbs_EDGE) || (aType == TopAbs_WIRE)) 
335     theDrawer->SetDeviationCoefficient(1.e-4);
336 }
337
338 Quantity_Color color(const std::string& theSection,
339                      const std::string& theName,
340                      const std::string& theDefault)
341 {
342   std::vector<int> aColor = Config_PropManager::color(theSection, theName, theDefault);
343   return Quantity_Color(aColor[0] / 255., aColor[1] / 255., aColor[2] / 255., Quantity_TOC_RGB);
344 }
345
346 ObjectPtr getObject(const AttributePtr& theAttribute)
347 {
348   ObjectPtr anObject;
349   std::string anAttrType = theAttribute->attributeType();
350   if (anAttrType == ModelAPI_AttributeRefAttr::typeId()) {
351     AttributeRefAttrPtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
352     if (anAttr != NULL && anAttr->isObject())
353       anObject = anAttr->object();
354   }
355   if (anAttrType == ModelAPI_AttributeSelection::typeId()) {
356     AttributeSelectionPtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
357     if (anAttr != NULL)
358       anObject = anAttr->context();
359   }
360   if (anAttrType == ModelAPI_AttributeReference::typeId()) {
361     AttributeReferencePtr anAttr = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
362     if (anAttr.get() != NULL)
363       anObject = anAttr->value();
364   }
365   return anObject;
366 }
367
368 TopAbs_ShapeEnum getCompoundSubType(const TopoDS_Shape& theShape)
369 {
370   TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
371
372   // for compounds check sub-shapes: it may be compound of needed type:
373   // Booleans may produce compounds of Solids
374   if (aShapeType == TopAbs_COMPOUND) {
375     for(TopoDS_Iterator aSubs(theShape); aSubs.More(); aSubs.Next()) {
376       if (!aSubs.Value().IsNull()) {
377         TopAbs_ShapeEnum aSubType = aSubs.Value().ShapeType();
378         if (aSubType == TopAbs_COMPOUND) { // compound of compound(s)
379           aShapeType = TopAbs_COMPOUND;
380           break;
381         }
382         if (aShapeType == TopAbs_COMPOUND) {
383           aShapeType = aSubType;
384         } else if (aShapeType != aSubType) { // compound of shapes of different types
385           aShapeType = TopAbs_COMPOUND;
386           break;
387         }
388       }
389     }
390   }
391   return aShapeType;
392 }
393
394 void getParameters(QStringList& theParameters)
395 {
396   theParameters.clear();
397
398   SessionPtr aSession = ModelAPI_Session::get();
399   std::list<DocumentPtr> aDocList;
400   DocumentPtr anActiveDocument = aSession->activeDocument();
401   DocumentPtr aRootDocument = aSession->moduleDocument();
402   aDocList.push_back(anActiveDocument);
403   if (anActiveDocument != aRootDocument) {
404     aDocList.push_back(aRootDocument);
405   }
406   std::string aGroupId = ModelAPI_ResultParameter::group();
407   for(std::list<DocumentPtr>::const_iterator it = aDocList.begin(); it != aDocList.end(); ++it) {
408     DocumentPtr aDocument = *it;
409     int aSize = aDocument->size(aGroupId);
410     for (int i = 0; i < aSize; i++) {
411       ObjectPtr anObject = aDocument->object(aGroupId, i);
412       std::string aParameterName = anObject->data()->name();
413       theParameters.append(aParameterName.c_str());
414     }
415   }
416 }
417
418 std::string findGreedAttribute(ModuleBase_IWorkshop* theWorkshop, const FeaturePtr& theFeature)
419 {
420   std::string anAttributeId;
421
422   std::string aXmlCfg, aDescription;
423   theWorkshop->module()->getXMLRepresentation(theFeature->getKind(), aXmlCfg, aDescription);
424
425   ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
426   std::string anAttributeTitle;
427   aFactory.getGreedAttribute(anAttributeId);
428
429   return anAttributeId;
430 }
431
432 void setObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
433                const GeomShapePtr& theShape, ModuleBase_IWorkshop* theWorkshop,
434                const bool theTemporarily)
435 {
436   if (!theAttribute.get())
437     return;
438
439   std::string aType = theAttribute->attributeType();
440   if (aType == ModelAPI_AttributeReference::typeId()) {
441     AttributeReferencePtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
442     ObjectPtr aObject = aRef->value();
443     if (!(aObject && aObject->isSame(theObject))) {
444       aRef->setValue(theObject);
445     }
446   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
447     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
448
449     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
450     if (anAttribute.get())
451       aRefAttr->setAttr(anAttribute);
452     else {
453       ObjectPtr aObject = aRefAttr->object();
454       if (!(aObject && aObject->isSame(theObject))) {
455         aRefAttr->setObject(theObject);
456       }
457     }
458   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
459     AttributeSelectionPtr aSelectAttr =
460                              std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
461     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
462     if (aSelectAttr.get() != NULL) {
463       aSelectAttr->setValue(aResult, theShape, theTemporarily);
464     }
465   }
466   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
467     AttributeSelectionListPtr aSelectionListAttr =
468                          std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
469     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
470     if (!aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
471       aSelectionListAttr->append(aResult, theShape, theTemporarily);
472   }
473   else if (aType == ModelAPI_AttributeRefList::typeId()) {
474     AttributeRefListPtr aRefListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
475     if (!aRefListAttr->isInList(theObject))
476       aRefListAttr->append(theObject);
477   }
478   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
479     AttributeRefAttrListPtr aRefAttrListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
480     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
481
482     if (anAttribute.get()) {
483       if (!aRefAttrListAttr->isInList(anAttribute))
484         aRefAttrListAttr->append(anAttribute);
485     }
486     else {
487       if (!aRefAttrListAttr->isInList(theObject))
488         aRefAttrListAttr->append(theObject);
489     }
490   }
491 }
492
493 GeomShapePtr getShape(const AttributePtr& theAttribute, ModuleBase_IWorkshop* theWorkshop)
494 {
495   GeomShapePtr aShape;
496   if (!theAttribute.get())
497     return aShape;
498
499   std::string aType = theAttribute->attributeType();
500   if (aType == ModelAPI_AttributeReference::typeId()) {
501   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
502     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
503     if (aRefAttr.get() && !aRefAttr->isObject()) {
504       AttributePtr anAttribute = aRefAttr->attr();
505       aShape = theWorkshop->module()->findShape(anAttribute);
506     }
507   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
508     AttributeSelectionPtr aSelectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>
509                                                                                  (theAttribute);
510     aShape = aSelectAttr->value();
511   }
512   return aShape;
513 }
514
515 } // namespace ModuleBase_Tools
516
517