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