Salome HOME
Issue #2571: Clear error flag if the control is initialized from the attribute
[modules/shaper.git] / src / ModuleBase / ModuleBase_Tools.cpp
1 // Copyright (C) 2014-2017  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include "ModuleBase_Tools.h"
22
23 #include <ModuleBase_ParamIntSpinBox.h>
24 #include <ModuleBase_ParamSpinBox.h>
25 #include <ModuleBase_WidgetFactory.h>
26 #include <ModuleBase_IWorkshop.h>
27 #include <ModuleBase_IModule.h>
28 #include <ModuleBase_IViewer.h>
29 #include <ModuleBase_IconFactory.h>
30 #include <ModuleBase_ResultPrs.h>
31 #include <ModuleBase_ViewerPrs.h>
32
33 #include <ModelAPI_Attribute.h>
34 #include <ModelAPI_AttributeRefAttr.h>
35 #include <ModelAPI_AttributeReference.h>
36 #include <ModelAPI_AttributeSelection.h>
37 #include <ModelAPI_AttributeSelectionList.h>
38 #include <ModelAPI_AttributeRefList.h>
39 #include <ModelAPI_AttributeRefAttrList.h>
40 #include <ModelAPI_ResultPart.h>
41 #include <ModelAPI_ResultConstruction.h>
42 #include <ModelAPI_AttributeString.h>
43 #include <ModelAPI_Expression.h>
44 #include <Events_Loop.h>
45
46 #include <ModelAPI_Data.h>
47 #include <ModelAPI_Result.h>
48 #include <ModelAPI_ResultCompSolid.h>
49 #include <ModelAPI_ResultParameter.h>
50 #include <ModelAPI_Tools.h>
51 #include <ModelAPI_Session.h>
52 #include <ModelAPI_Events.h>
53 #include <ModelAPI_Folder.h>
54
55 #include <ModelGeomAlgo_Point2D.h>
56
57 #include <StdSelect_BRepOwner.hxx>
58 #include <TopoDS_Iterator.hxx>
59 #include <AIS_InteractiveContext.hxx>
60 #include <Prs3d_LineAspect.hxx>
61 #include <Prs3d_PlaneAspect.hxx>
62
63 #include <GeomDataAPI_Point2D.h>
64 #include <Events_InfoMessage.h>
65 #include <GeomAPI_ShapeExplorer.h>
66
67 #include <Config_PropManager.h>
68 #include <Config_Translator.h>
69
70 #include <Prs3d_PointAspect.hxx>
71 #include <Graphic3d_AspectMarker3d.hxx>
72
73 #include <Image_AlienPixMap.hxx>
74
75 #include <QWidget>
76 #include <QLayout>
77 #include <QPainter>
78 #include <QBitmap>
79 #include <QDoubleSpinBox>
80 #include <QGraphicsDropShadowEffect>
81 #include <QColor>
82 #include <QApplication>
83 #include <QMessageBox>
84 #include <QAction>
85 #include <QTextCodec>
86
87 #include <sstream>
88 #include <string>
89
90 #ifdef WIN32
91 #pragma warning(disable : 4996) // for getenv
92 #endif
93
94 const double tolerance = 1e-7;
95 const double DEFAULT_DEVIATION_COEFFICIENT = 1.e-4;
96
97 //#define DEBUG_ACTIVATE_WINDOW
98 //#define DEBUG_SET_FOCUS
99
100 #ifdef WIN32
101 # define FSEP "\\"
102 #else
103 # define FSEP "/"
104 #endif
105
106 namespace ModuleBase_Tools {
107
108 //******************************************************************
109
110 //******************************************************************
111
112 void adjustMargins(QWidget* theWidget)
113 {
114   if(!theWidget)
115     return;
116   adjustMargins(theWidget->layout());
117 }
118
119 void adjustMargins(QLayout* theLayout)
120 {
121   if(!theLayout)
122     return;
123   theLayout->setContentsMargins(2, 5, 2, 5);
124   theLayout->setSpacing(4);
125 }
126
127 void zeroMargins(QWidget* theWidget)
128 {
129   if(!theWidget)
130     return;
131   zeroMargins(theWidget->layout());
132 }
133
134 void zeroMargins(QLayout* theLayout)
135 {
136   if(!theLayout)
137     return;
138   theLayout->setContentsMargins(0, 0, 0, 0);
139   theLayout->setSpacing(5);
140 }
141
142 void activateWindow(QWidget* theWidget, const QString& theInfo)
143 {
144   if (theWidget) {
145     theWidget->activateWindow();
146     theWidget->raise();
147   }
148
149 #ifdef DEBUG_ACTIVATE_WINDOW
150   qDebug(QString("activateWindow: %1").arg(theInfo).toStdString().c_str());
151 #endif
152 }
153
154 void setFocus(QWidget* theWidget, const QString& theInfo)
155 {
156   activateWindow(theWidget);
157   theWidget->setFocus();
158   // rectangle of focus is not visible on tool button widgets
159   theWidget->repaint();
160 #ifdef DEBUG_SET_FOCUS
161   qDebug(QString("setFocus: %1").arg(theInfo).toStdString().c_str());
162 #endif
163 }
164
165 void setShadowEffect(QWidget* theWidget, const bool isSetEffect)
166 {
167   if (isSetEffect) {
168     QGraphicsDropShadowEffect* aGlowEffect = new QGraphicsDropShadowEffect();
169     aGlowEffect->setOffset(.0);
170     aGlowEffect->setBlurRadius(10.0);
171     aGlowEffect->setColor(QColor(0, 170, 255)); // Light-blue color, #00AAFF
172     theWidget->setGraphicsEffect(aGlowEffect);
173   }
174   else {
175     QGraphicsEffect* anEffect = theWidget->graphicsEffect();
176     if(anEffect)
177       anEffect->deleteLater();
178     theWidget->setGraphicsEffect(NULL);
179   }
180 }
181
182 QPixmap composite(const QString& theAdditionalIcon, const QString& theIcon)
183 {
184   QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
185   QImage anAditional(theAdditionalIcon);
186
187   if (anIcon.isNull())
188     return QPixmap();
189
190   int anAddWidth = anAditional.width();
191   int anAddHeight = anAditional.height();
192
193   int aWidth = anIcon.width();
194   int aHeight = anIcon.height();
195
196   int aStartWidthPos = aWidth - anAddWidth - 1;
197   int aStartHeightPos = aHeight - anAddHeight - 1;
198
199   for (int i = 0; i < anAddWidth && i + aStartWidthPos < aWidth; i++)
200   {
201     for (int j = 0; j < anAddHeight && j + aStartHeightPos < aHeight; j++)
202     {
203       if (qAlpha(anAditional.pixel(i, j)) > 0)
204         anIcon.setPixel(i + aStartWidthPos, j + aStartHeightPos, anAditional.pixel(i, j));
205     }
206   }
207   return QPixmap::fromImage(anIcon);
208 }
209
210 QPixmap lighter(const QString& theIcon, const int theLighterValue)
211 {
212   QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
213   if (anIcon.isNull())
214     return QPixmap();
215
216   QImage aResult = ModuleBase_IconFactory::loadImage(theIcon);
217   for (int i = 0; i < anIcon.width(); i++)
218   {
219     for (int j = 0; j < anIcon.height(); j++)
220     {
221       QRgb anRgb = anIcon.pixel(i, j);
222       QColor aPixelColor(qRed(anRgb), qGreen(anRgb), qBlue(anRgb),
223                          qAlpha(aResult.pixel(i, j)));
224
225       QColor aLighterColor = aPixelColor.lighter(theLighterValue);
226       aResult.setPixel(i, j, qRgba(aLighterColor.red(), aLighterColor.green(),
227                                     aLighterColor.blue(), aLighterColor.alpha()));
228     }
229   }
230   return QPixmap::fromImage(aResult);
231 }
232
233 void setSpinText(ModuleBase_ParamSpinBox* theSpin, const QString& theText)
234 {
235   if (theSpin->text() == theText)
236     return;
237   // In order to avoid extra text setting because it will
238   // reset cursor position in control
239   bool isBlocked = theSpin->blockSignals(true);
240   theSpin->setText(theText);
241   theSpin->blockSignals(isBlocked);
242 }
243
244 void setSpinValue(QDoubleSpinBox* theSpin, double theValue)
245 {
246   if (fabs(theSpin->value() - theValue) < tolerance)
247     return;
248   bool isBlocked = theSpin->blockSignals(true);
249   theSpin->setValue(theValue);
250   theSpin->blockSignals(isBlocked);
251 }
252
253 void setSpinValue(ModuleBase_ParamSpinBox* theSpin, double theValue)
254 {
255   if (fabs(theSpin->value() - theValue) < tolerance)
256     return;
257   bool isBlocked = theSpin->blockSignals(true);
258   theSpin->setValue(theValue);
259   theSpin->blockSignals(isBlocked);
260 }
261
262 void setSpinText(ModuleBase_ParamIntSpinBox* theSpin, const QString& theText)
263 {
264   // In order to avoid extra text setting because it will
265   // reset cursor position in control
266   if (theSpin->text() == theText)
267     return;
268   bool isBlocked = theSpin->blockSignals(true);
269   theSpin->setText(theText);
270   theSpin->blockSignals(isBlocked);
271 }
272
273 void setSpinValue(ModuleBase_ParamIntSpinBox* theSpin, int theValue)
274 {
275   if (theSpin->value() == theValue)
276     return;
277   bool isBlocked = theSpin->blockSignals(true);
278   theSpin->setValue(theValue);
279   theSpin->blockSignals(isBlocked);
280 }
281
282 QAction* createAction(const QIcon& theIcon, const QString& theText,
283                       QObject* theParent, const QObject* theReceiver,
284                       const char* theMember, const QString& theToolTip,
285                       const QString& theStatusTip)
286 {
287   QAction* anAction = new QAction(theIcon, theText, theParent);
288   anAction->setToolTip(theToolTip.isEmpty() ? theText : theToolTip);
289   anAction->setStatusTip(!theStatusTip.isEmpty() ? theStatusTip :
290                                                    (!theToolTip.isEmpty() ? theToolTip : theText));
291   if (theReceiver)
292     QObject::connect(anAction, SIGNAL(triggered(bool)), theReceiver, theMember);
293
294   return anAction;
295 }
296
297 #ifdef _DEBUG
298 QString objectName(const ObjectPtr& theObj)
299 {
300   if (!theObj.get())
301     return "";
302
303   return theObj->data()->name().c_str();
304 }
305
306 QString objectInfo(const ObjectPtr& theObj, const bool isUseAttributesInfo)
307 {
308   QString aFeatureStr = "feature";
309   if (!theObj.get())
310     return aFeatureStr;
311
312   std::ostringstream aPtrStr;
313   aPtrStr << "[" << theObj.get() << "]";
314
315   ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theObj);
316   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
317   if(aRes.get()) {
318     aFeatureStr.append(QString("(result%1)").arg(aPtrStr.str().c_str()).toStdString() .c_str());
319     if (aRes->isDisabled())
320       aFeatureStr.append("[disabled]");
321     if (aRes->isConcealed())
322       aFeatureStr.append("[concealed]");
323     if (ModelAPI_Tools::hasSubResults(aRes))
324       aFeatureStr.append("[hasSubResults]");
325
326     aFeature = ModelAPI_Feature::feature(aRes);
327   }
328   else
329     aFeatureStr.append(aPtrStr.str().c_str());
330
331   if (aFeature.get()) {
332     aFeatureStr.append(QString(": %1").arg(aFeature->getKind().c_str()).toStdString().c_str());
333     if (aFeature->data()->isValid()) {
334       aFeatureStr.append(QString(", name=%1").arg(theObj->data()->name().c_str()).toStdString()
335                                                                                        .c_str());
336     }
337     if (isUseAttributesInfo) {
338       std::set<std::shared_ptr<ModelAPI_Attribute> > anAttributes;
339       std::string aPointsInfo = ModelGeomAlgo_Point2D::getPontAttributesInfo(aFeature,
340                                                                           anAttributes).c_str();
341       if (!aPointsInfo.empty())
342         aFeatureStr.append(QString(", attributes: %1")
343           .arg(aPointsInfo.c_str()).toStdString().c_str());
344     }
345   }
346
347   return aFeatureStr;
348 }
349 #endif
350
351 typedef QMap<QString, int> ShapeTypes;
352 static ShapeTypes myShapeTypes;
353
354 int shapeType(const QString& theType)
355 {
356   if (myShapeTypes.count() == 0) {
357     myShapeTypes["compound"]   = TopAbs_COMPOUND;
358     myShapeTypes["compounds"]  = TopAbs_COMPOUND;
359     myShapeTypes["compsolid"]  = TopAbs_COMPSOLID;
360     myShapeTypes["compsolids"] = TopAbs_COMPSOLID;
361     myShapeTypes["solid"]      = TopAbs_SOLID;
362     myShapeTypes["solids"]     = TopAbs_SOLID;
363     myShapeTypes["shell"]      = TopAbs_SHELL;
364     myShapeTypes["shells"]     = TopAbs_SHELL;
365     myShapeTypes["face"]       = TopAbs_FACE;
366     myShapeTypes["faces"]      = TopAbs_FACE;
367     myShapeTypes["wire"]       = TopAbs_WIRE;
368     myShapeTypes["wires"]      = TopAbs_WIRE;
369     myShapeTypes["edge"]       = TopAbs_EDGE;
370     myShapeTypes["edges"]      = TopAbs_EDGE;
371     myShapeTypes["vertex"]     = TopAbs_VERTEX;
372     myShapeTypes["vertices"]   = TopAbs_VERTEX;
373     myShapeTypes["object"]     = ModuleBase_ResultPrs::Sel_Result;
374     myShapeTypes["objects"]    = ModuleBase_ResultPrs::Sel_Result;
375   }
376   QString aType = theType.toLower();
377   if(myShapeTypes.contains(aType))
378     return myShapeTypes[aType];
379   Events_InfoMessage("ModuleBase_Tools", "Shape type defined in XML is not implemented!").send();
380   return TopAbs_SHAPE;
381 }
382
383 void checkObjects(const QObjectPtrList& theObjects, bool& hasResult, bool& hasFeature,
384                   bool& hasParameter, bool& hasCompositeOwner, bool& hasResultInHistory,
385                   bool& hasFolder)
386 {
387   hasResult = false;
388   hasFeature = false;
389   hasParameter = false;
390   hasCompositeOwner = false;
391   hasResultInHistory = false;
392   hasFolder = false;
393   foreach(ObjectPtr aObj, theObjects) {
394     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
395     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
396     FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(aObj);
397     ResultParameterPtr aConstruction = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aResult);
398
399     hasResult |= (aResult.get() != NULL);
400     hasFeature |= (aFeature.get() != NULL);
401     hasFolder |= (aFolder.get() != NULL);
402     hasParameter |= (aConstruction.get() != NULL);
403     if (hasFeature)
404       hasCompositeOwner |= (ModelAPI_Tools::compositeOwner(aFeature) != NULL);
405
406     if (!hasResultInHistory && aResult.get()) {
407       FeaturePtr aFeature = ModelAPI_Feature::feature(aResult);
408       hasResultInHistory = aFeature.get() && aFeature->isInHistory();
409     }
410
411     if (hasFeature && hasResult  && hasParameter && hasCompositeOwner && hasFeature)
412       break;
413   }
414 }
415
416 /*bool setDefaultDeviationCoefficient(std::shared_ptr<GeomAPI_Shape> theGeomShape)
417 {
418   if (!theGeomShape.get())
419     return false;
420   // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
421   // correction of deviation for them should not influence to the application performance
422   GeomAPI_ShapeExplorer anExp(theGeomShape, GeomAPI_Shape::FACE);
423   bool anEmpty = anExp.empty();
424   return !anExp.more();
425 }*/
426
427 /*void setDefaultDeviationCoefficient(const std::shared_ptr<ModelAPI_Result>& theResult,
428                                     const Handle(Prs3d_Drawer)& theDrawer)
429 {
430   if (!theResult.get())
431     return;
432   bool aUseDeviation = false;
433
434   std::string aResultGroup = theResult->groupName();
435   if (aResultGroup == ModelAPI_ResultConstruction::group())
436     aUseDeviation = true;
437   else if (aResultGroup == ModelAPI_ResultBody::group()) {
438     GeomShapePtr aGeomShape = theResult->shape();
439     if (aGeomShape.get())
440       aUseDeviation = setDefaultDeviationCoefficient(aGeomShape);
441   }
442   if (aUseDeviation)
443     theDrawer->SetDeviationCoefficient(DEFAULT_DEVIATION_COEFFICIENT);
444 }
445 */
446 void setDefaultDeviationCoefficient(const TopoDS_Shape& theShape,
447                                     const Handle(Prs3d_Drawer)& theDrawer)
448 {
449   if (theShape.IsNull())
450     return;
451
452   std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape());
453   aGeomShape->setImpl(new TopoDS_Shape(theShape));
454
455   // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
456   // correction of deviation for them should not influence to the application performance
457   GeomAPI_ShapeExplorer anExp(aGeomShape, GeomAPI_Shape::FACE);
458   bool isConstruction = !anExp.more();
459
460   double aDeflection;
461   if (isConstruction)
462     aDeflection = Config_PropManager::real("Visualization", "construction_deflection");
463   else
464     aDeflection = Config_PropManager::real("Visualization", "body_deflection");
465
466   theDrawer->SetDeviationCoefficient(aDeflection);
467 }
468
469 Quantity_Color color(const std::string& theSection,
470                      const std::string& theName)
471 {
472   std::vector<int> aColor = Config_PropManager::color(theSection, theName);
473   return Quantity_Color(aColor[0] / 255., aColor[1] / 255., aColor[2] / 255., Quantity_TOC_RGB);
474 }
475
476 ObjectPtr getObject(const AttributePtr& theAttribute)
477 {
478   ObjectPtr anObject;
479   std::string anAttrType = theAttribute->attributeType();
480   if (anAttrType == ModelAPI_AttributeRefAttr::typeId()) {
481     AttributeRefAttrPtr anAttr =
482       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
483     if (anAttr != NULL && anAttr->isObject())
484       anObject = anAttr->object();
485   }
486   if (anAttrType == ModelAPI_AttributeSelection::typeId()) {
487     AttributeSelectionPtr anAttr =
488       std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
489     if (anAttr != NULL)
490       anObject = anAttr->context();
491   }
492   if (anAttrType == ModelAPI_AttributeReference::typeId()) {
493     AttributeReferencePtr anAttr =
494       std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
495     if (anAttr.get() != NULL)
496       anObject = anAttr->value();
497   }
498   return anObject;
499 }
500
501 TopAbs_ShapeEnum getCompoundSubType(const TopoDS_Shape& theShape)
502 {
503   TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
504
505   // for compounds check sub-shapes: it may be compound of needed type:
506   // Booleans may produce compounds of Solids
507   if (aShapeType == TopAbs_COMPOUND) {
508     for(TopoDS_Iterator aSubs(theShape); aSubs.More(); aSubs.Next()) {
509       if (!aSubs.Value().IsNull()) {
510         TopAbs_ShapeEnum aSubType = aSubs.Value().ShapeType();
511         if (aSubType == TopAbs_COMPOUND) { // compound of compound(s)
512           aShapeType = TopAbs_COMPOUND;
513           break;
514         }
515         if (aShapeType == TopAbs_COMPOUND) {
516           aShapeType = aSubType;
517         } else if (aShapeType != aSubType) { // compound of shapes of different types
518           aShapeType = TopAbs_COMPOUND;
519           break;
520         }
521       }
522     }
523   }
524   return aShapeType;
525 }
526
527 TopoDS_Shape getSelectedShape(const std::shared_ptr<ModuleBase_ViewerPrs>& thePrs)
528 {
529   if (thePrs->shape().get())
530     return thePrs->shape()->impl<TopoDS_Shape>();
531
532   Handle(StdSelect_BRepOwner) anOwner = Handle(StdSelect_BRepOwner)::DownCast(thePrs->owner());
533   if (!anOwner.IsNull())
534     return anOwner->Shape();
535
536   return TopoDS_Shape();
537 }
538
539 void getParameters(QStringList& theParameters)
540 {
541   theParameters.clear();
542
543   SessionPtr aSession = ModelAPI_Session::get();
544   std::list<DocumentPtr> aDocList;
545   DocumentPtr anActiveDocument = aSession->activeDocument();
546   DocumentPtr aRootDocument = aSession->moduleDocument();
547   aDocList.push_back(anActiveDocument);
548   if (anActiveDocument != aRootDocument) {
549     aDocList.push_back(aRootDocument);
550   }
551   std::string aGroupId = ModelAPI_ResultParameter::group();
552   for(std::list<DocumentPtr>::const_iterator it = aDocList.begin(); it != aDocList.end(); ++it) {
553     DocumentPtr aDocument = *it;
554     int aSize = aDocument->size(aGroupId);
555     for (int i = 0; i < aSize; i++) {
556       ObjectPtr anObject = aDocument->object(aGroupId, i);
557       std::string aParameterName = anObject->data()->name();
558       theParameters.append(aParameterName.c_str());
559     }
560   }
561 }
562
563 std::string findGreedAttribute(ModuleBase_IWorkshop* theWorkshop,
564                                const FeaturePtr& theFeature)
565 {
566   std::string anAttributeId;
567
568   std::string aXmlCfg, aDescription;
569   theWorkshop->module()->getXMLRepresentation(theFeature->getKind(), aXmlCfg, aDescription);
570
571   ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
572   std::string anAttributeTitle;
573   aFactory.getGreedAttribute(anAttributeId);
574
575   return anAttributeId;
576 }
577
578 bool hasObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
579                const std::shared_ptr<GeomAPI_Shape>& theShape,
580                ModuleBase_IWorkshop* theWorkshop,
581                const bool theTemporarily)
582 {
583   bool aHasObject = false;
584   if (!theAttribute.get())
585     return aHasObject;
586
587   std::string aType = theAttribute->attributeType();
588   if (aType == ModelAPI_AttributeReference::typeId()) {
589     AttributeReferencePtr aRef =
590       std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
591     ObjectPtr aObject = aRef->value();
592     aHasObject = aObject && aObject->isSame(theObject);
593     //if (!(aObject && aObject->isSame(theObject))) {
594     //  aRef->setValue(theObject);
595     //}
596   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
597     AttributeRefAttrPtr aRefAttr =
598       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
599
600     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
601     if (anAttribute.get()) {
602       //aRefAttr->setAttr(anAttribute);
603     }
604     else {
605       ObjectPtr aObject = aRefAttr->object();
606       aHasObject = aObject && aObject->isSame(theObject);
607       //if (!(aObject && aObject->isSame(theObject))) {
608       //  aRefAttr->setObject(theObject);
609       //}
610     }
611   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
612     /*AttributeSelectionPtr aSelectAttr =
613                              std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
614     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
615     if (aSelectAttr.get() != NULL) {
616       aSelectAttr->setValue(aResult, theShape, theTemporarily);
617     }*/
618   }
619   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
620     AttributeSelectionListPtr aSelectionListAttr =
621                          std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
622     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
623     aHasObject = aSelectionListAttr->isInList(aResult, theShape, theTemporarily);
624   }
625   else if (aType == ModelAPI_AttributeRefList::typeId()) {
626     AttributeRefListPtr aRefListAttr =
627       std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
628     aHasObject = aRefListAttr->isInList(theObject);
629     //if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
630     //  aRefListAttr->append(theObject);
631   }
632   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
633     AttributeRefAttrListPtr aRefAttrListAttr =
634       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
635     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
636
637     if (anAttribute.get()) {
638       aHasObject = aRefAttrListAttr->isInList(anAttribute);
639       //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
640       //  aRefAttrListAttr->append(anAttribute);
641     }
642     else {
643       aHasObject = aRefAttrListAttr->isInList(theObject);
644       //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
645       //  aRefAttrListAttr->append(theObject);
646     }
647   }
648   return aHasObject;
649 }
650
651 bool setObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
652                const GeomShapePtr& theShape, ModuleBase_IWorkshop* theWorkshop,
653                const bool theTemporarily, const bool theCheckIfAttributeHasObject)
654 {
655   if (!theAttribute.get())
656     return false;
657
658   bool isDone = true;
659   std::string aType = theAttribute->attributeType();
660   if (aType == ModelAPI_AttributeReference::typeId()) {
661     AttributeReferencePtr aRef =
662       std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
663     ObjectPtr aObject = aRef->value();
664     if (!(aObject && aObject->isSame(theObject))) {
665       aRef->setValue(theObject);
666     }
667   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
668     AttributeRefAttrPtr aRefAttr =
669       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
670
671     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
672     if (anAttribute.get())
673       aRefAttr->setAttr(anAttribute);
674     else {
675       ObjectPtr aObject = aRefAttr->object();
676       if (!(aObject && aObject->isSame(theObject))) {
677         aRefAttr->setObject(theObject);
678       }
679     }
680   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
681     AttributeSelectionPtr aSelectAttr =
682                              std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
683     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
684     if (aSelectAttr.get() != NULL) {
685       aSelectAttr->setValue(aResult, theShape, theTemporarily);
686     }
687   }
688   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
689     AttributeSelectionListPtr aSelectionListAttr =
690                          std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
691     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
692     if (!theCheckIfAttributeHasObject ||
693         !aSelectionListAttr->isInList(aResult, theShape, theTemporarily))
694       aSelectionListAttr->append(aResult, 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 = 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 (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
996       aPartFeatureNames.append(aFeature->name().c_str());
997     else
998       anOtherFeatureNames.append(aFeature->name().c_str());
999   }
1000   aPartFeatureNames.sort();
1001   anOtherFeatureNames.sort();
1002
1003   bool aCanReplaceParameters = !aFeaturesRefsToParameterOnly.empty();
1004
1005   QMessageBox aMessageBox(theParent);
1006   aMessageBox.setWindowTitle(QObject::tr("Delete features"));
1007   aMessageBox.setIcon(QMessageBox::Warning);
1008   aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1009   aMessageBox.setDefaultButton(QMessageBox::No);
1010
1011   QString aText;
1012   if (!thePrefixInfo.empty())
1013     aText = thePrefixInfo.c_str();
1014   QString aSep = ", ";
1015   if (!aPartFeatureNames.empty()) {
1016     aText += QString(QObject::tr("The following parts will be deleted: %1.\n"))
1017              .arg(aPartFeatureNames.join(aSep));
1018   }
1019   if (!aNotActivatedDocWrn.isEmpty())
1020     aText += aNotActivatedDocWrn;
1021   if (!anOtherFeatureNames.empty()) {
1022     const char* aMsg = "Features are used in the following features: %1.\nThese "
1023                        "features will be deleted.\n";
1024     aText += QString(QObject::tr(aMsg))
1025                      .arg(anOtherFeatureNames.join(aSep));
1026   }
1027   if (!aParamFeatureNames.empty()) {
1028     const char* aMsg = "Parameters are used directly and through a sequence "
1029                        "of dependencies in the following features: %1.\nThese features will "
1030                        "be deleted.\nOr parameters could be replaced by their values.\n";
1031     aText += QString(QObject::tr(aMsg))
1032                      .arg(aParamFeatureNames.join(aSep));
1033     QPushButton *aReplaceButton =
1034       aMessageBox.addButton(QObject::tr("Replace"), QMessageBox::ActionRole);
1035   }
1036
1037   if (!aText.isEmpty()) {
1038     aText += "Would you like to continue?";
1039     aMessageBox.setText(aText);
1040     aMessageBox.exec();
1041     QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1042
1043     if (aButtonRole == QMessageBox::NoRole)
1044       return false;
1045
1046     if (aButtonRole == QMessageBox::ActionRole) {
1047       foreach (FeaturePtr aObj, aParameterFeatures)
1048         ModelAPI_ReplaceParameterMessage::send(aObj, 0);
1049     }
1050     else
1051       theReferencesToDelete.insert(aFeaturesRefsToParameterOnly.begin(),
1052                                    aFeaturesRefsToParameterOnly.end());
1053   }
1054   return true;
1055 }
1056
1057 //**************************************************************
1058 void convertToFeatures(const QObjectPtrList& theObjects, std::set<FeaturePtr>& theFeatures)
1059 {
1060   QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1061   for(; anIt != aLast; anIt++) {
1062     ObjectPtr anObject = *anIt;
1063     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1064     // for parameter result, use the corresponded reature to be removed
1065     if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1066       aFeature = ModelAPI_Feature::feature(anObject);
1067     }
1068     if (aFeature.get())
1069       theFeatures.insert(aFeature);
1070   }
1071 }
1072
1073 //**************************************************************
1074 void convertToFolders(const QObjectPtrList& theObjects,
1075                                          std::set<FolderPtr>& theFolders)
1076 {
1077   QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1078   for(; anIt != aLast; anIt++) {
1079     ObjectPtr anObject = *anIt;
1080     FolderPtr aFeature = std::dynamic_pointer_cast<ModelAPI_Folder>(anObject);
1081     if (aFeature.get())
1082       theFolders.insert(aFeature);
1083   }
1084 }
1085
1086
1087 //**************************************************************
1088 QString translate(const Events_InfoMessage& theMessage)
1089 {
1090   QString aMessage;
1091
1092   if (!theMessage.empty()) {
1093     std::string aStr = Config_Translator::translate(theMessage);
1094     if (!aStr.empty()) {
1095       std::string aCodec = Config_Translator::codec(theMessage);
1096       aMessage = QTextCodec::codecForName(aCodec.c_str())->toUnicode(aStr.c_str());
1097     }
1098   }
1099
1100   return aMessage;
1101 }
1102
1103 QString translate(const std::string& theContext, const std::string& theMessage)
1104 {
1105   QString aMessage;
1106
1107   if (!theMessage.empty()) {
1108     std::string aStr = Config_Translator::translate(theContext, theMessage);
1109     if (!aStr.empty()) {
1110       std::string aCodec = Config_Translator::codec(theContext);
1111       aMessage = QTextCodec::codecForName(aCodec.c_str())->toUnicode(aStr.c_str());
1112     }
1113   }
1114
1115   return aMessage;
1116 }
1117
1118 void setPointBallHighlighting(AIS_Shape* theAIS)
1119 {
1120   static Handle(Image_AlienPixMap) aPixMap;
1121   if(aPixMap.IsNull()) {
1122     // Load icon for the presentation
1123     std::string aFile;
1124     char* anEnv = getenv("SHAPER_ROOT_DIR");
1125     if(anEnv) {
1126       aFile = std::string(anEnv) +
1127         FSEP + "share" + FSEP + "salome" + FSEP + "resources" + FSEP + "shaper";
1128     } else {
1129       anEnv = getenv("OPENPARTS_ROOT_DIR");
1130       if (anEnv)
1131         aFile = std::string(anEnv) + FSEP + "resources";
1132     }
1133
1134     aFile += FSEP;
1135     static const std::string aMarkerName = "marker_dot.png";
1136     aFile += aMarkerName;
1137     aPixMap = new Image_AlienPixMap();
1138     if(!aPixMap->Load(aFile.c_str())) {
1139       // The icon for constraint is not found
1140       static const std::string aMsg =
1141         "Error: Point market not found by path: \"" + aFile + "\". Falling back.";
1142       //Events_InfoMessage("ModuleBase_Tools::setPointBallHighlighting", aMsg).send();
1143     }
1144   }
1145
1146   Handle(Graphic3d_AspectMarker3d) anAspect;
1147   Handle(Prs3d_Drawer) aDrawer = theAIS->DynamicHilightAttributes();
1148   if (aDrawer.IsNull()) {
1149     if (ModuleBase_IViewer::DefaultHighlightDrawer.IsNull())
1150       return;
1151     aDrawer = new Prs3d_Drawer(*ModuleBase_IViewer::DefaultHighlightDrawer);
1152     if (!aDrawer->HasOwnPointAspect()) {
1153       aDrawer->SetPointAspect(new Prs3d_PointAspect(Aspect_TOM_BALL, Quantity_NOC_BLACK, 2.0));
1154     }
1155   }
1156   if(aDrawer->HasOwnPointAspect()) {
1157     Handle(Prs3d_PointAspect) aPntAspect = aDrawer->PointAspect();
1158     if(aPixMap->IsEmpty()) {
1159       anAspect = aPntAspect->Aspect();
1160       anAspect->SetType(Aspect_TOM_BALL);
1161     } else {
1162       if(aPixMap->Format() == Image_PixMap::ImgGray) {
1163         aPixMap->SetFormat (Image_PixMap::ImgAlpha);
1164       } else if(aPixMap->Format() == Image_PixMap::ImgGrayF) {
1165         aPixMap->SetFormat (Image_PixMap::ImgAlphaF);
1166       }
1167       anAspect = new Graphic3d_AspectMarker3d(aPixMap);
1168       aPntAspect->SetAspect(anAspect);
1169     }
1170     aDrawer->SetPointAspect(aPntAspect);
1171           theAIS->SetDynamicHilightAttributes(aDrawer);
1172   }
1173 }
1174
1175 FeaturePtr createParameter(const QString& theText)
1176 {
1177   FeaturePtr aParameter;
1178   QStringList aList = theText.split("=");
1179   if (aList.count() != 2) {
1180     return aParameter;
1181   }
1182   QString aParamName = aList.at(0).trimmed();
1183
1184   if (isNameExist(aParamName, FeaturePtr())) {
1185     return aParameter;
1186   }
1187
1188   if (!ModelAPI_Expression::isVariable(aParamName.toStdString())) {
1189     return aParameter;
1190   }
1191
1192   QString aExpression = aList.at(1).trimmed();
1193   if (aExpression.isEmpty()) {
1194     return aParameter;
1195   }
1196
1197   SessionPtr aMgr = ModelAPI_Session::get();
1198   std::shared_ptr<ModelAPI_Document> aDoc = aMgr->activeDocument();
1199
1200   aParameter = aDoc->addFeature("Parameter");
1201   if (aParameter.get()) {
1202     AttributeStringPtr aNameAttr = aParameter->string("variable");
1203     aNameAttr->setValue(aParamName.toStdString());
1204
1205     AttributeStringPtr aExprAttr = aParameter->string("expression");
1206     aExprAttr->setValue(aExpression.toStdString());
1207     aParameter->execute();
1208
1209     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1210     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
1211   }
1212   return aParameter;
1213 }
1214
1215 void editParameter(FeaturePtr theParam, const QString& theText)
1216 {
1217   QStringList aList = theText.split("=");
1218   QString aParamName = aList.at(0).trimmed();
1219
1220   QString aExpression = aList.at(1).trimmed();
1221   if (aExpression.isEmpty()) {
1222     return;
1223   }
1224
1225   if (isNameExist(aParamName, theParam)) {
1226     return;
1227   }
1228   AttributeStringPtr aNameAttr = theParam->string("variable");
1229   aNameAttr->setValue(aParamName.toStdString());
1230
1231   AttributeStringPtr aExprAttr = theParam->string("expression");
1232   aExprAttr->setValue(aExpression.toStdString());
1233   theParam->execute();
1234
1235   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
1236 }
1237
1238 bool isNameExist(const QString& theName, FeaturePtr theIgnoreParameter)
1239 {
1240   SessionPtr aMgr = ModelAPI_Session::get();
1241   std::shared_ptr<ModelAPI_Document> aDoc = aMgr->activeDocument();
1242   FeaturePtr aParamFeature;
1243   int aNbFeatures = aDoc->numInternalFeatures();
1244   std::string aName = theName.toStdString();
1245   for (int i = 0; i < aNbFeatures; i++) {
1246     aParamFeature = aDoc->internalFeature(i);
1247     if (aParamFeature && aParamFeature->getKind() == "Parameter") {
1248       if ((theIgnoreParameter != aParamFeature) && (aParamFeature->name() == aName))
1249         return true;
1250     }
1251   }
1252   return false;
1253 }
1254
1255 FeaturePtr findParameter(const QString& theName)
1256 {
1257   SessionPtr aMgr = ModelAPI_Session::get();
1258   std::shared_ptr<ModelAPI_Document> aDoc = aMgr->activeDocument();
1259   FeaturePtr aParamFeature;
1260   int aNbFeatures = aDoc->numInternalFeatures();
1261   std::string aName = theName.toStdString();
1262   for (int i = 0; i < aNbFeatures; i++) {
1263     aParamFeature = aDoc->internalFeature(i);
1264     if (aParamFeature && aParamFeature->getKind() == "Parameter") {
1265       if (aParamFeature->name() == aName)
1266         return aParamFeature;
1267     }
1268   }
1269   return FeaturePtr();
1270 }
1271
1272
1273 //********************************************************************
1274 std::string generateName(const AttributePtr& theAttribute,
1275   ModuleBase_IWorkshop* theWorkshop)
1276 {
1277   std::string aName;
1278   if (theAttribute.get() != NULL) {
1279     ModuleBase_Operation* anOperation = theWorkshop->currentOperation();
1280
1281     FeaturePtr aFeature = ModelAPI_Feature::feature(theAttribute->owner());
1282     if (aFeature.get()) {
1283       std::string aXmlCfg, aDescription;
1284       theWorkshop->module()->getXMLRepresentation(aFeature->getKind(), aXmlCfg, aDescription);
1285
1286       ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
1287       std::string anAttributeTitle;
1288       aFactory.getAttributeTitle(theAttribute->id(), anAttributeTitle);
1289
1290       std::stringstream aStreamName;
1291       aStreamName << theAttribute->owner()->data()->name() << "/" << anAttributeTitle.c_str();
1292       aName = aStreamName.str();
1293     }
1294   }
1295   return aName;
1296 }
1297
1298 } // namespace ModuleBase_Tools
1299
1300