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