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