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