]> SALOME platform Git repositories - modules/shaper.git/blob - src/ModuleBase/ModuleBase_Tools.cpp
Salome HOME
Issue #3007: remove unnecessary activation of window
[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 <ModelAPI_ResultField.h>
44 #include <Events_Loop.h>
45
46 #include <ModelAPI_Data.h>
47 #include <ModelAPI_Result.h>
48 #include <ModelAPI_ResultParameter.h>
49 #include <ModelAPI_Tools.h>
50 #include <ModelAPI_Session.h>
51 #include <ModelAPI_Events.h>
52 #include <ModelAPI_Folder.h>
53
54 #include <ModelGeomAlgo_Point2D.h>
55
56 #include <StdSelect_BRepOwner.hxx>
57 #include <TopoDS_Iterator.hxx>
58 #include <AIS_InteractiveContext.hxx>
59 #include <Prs3d_LineAspect.hxx>
60 #include <Prs3d_PlaneAspect.hxx>
61
62 #include <GeomDataAPI_Point2D.h>
63 #include <Events_InfoMessage.h>
64 #include <GeomAPI_ShapeExplorer.h>
65
66 #include <Config_PropManager.h>
67 #include <Config_Translator.h>
68
69 #include <Prs3d_PointAspect.hxx>
70 #include <Graphic3d_AspectMarker3d.hxx>
71
72 #include <Image_AlienPixMap.hxx>
73
74 #include <QWidget>
75 #include <QLayout>
76 #include <QPainter>
77 #include <QBitmap>
78 #include <QDoubleSpinBox>
79 #include <QGraphicsDropShadowEffect>
80 #include <QColor>
81 #include <QApplication>
82 #include <QMessageBox>
83 #include <QAction>
84 #include <QTextCodec>
85
86 #include <sstream>
87 #include <string>
88
89 #ifdef WIN32
90 #pragma warning(disable : 4996) // for getenv
91 #endif
92
93 const double tolerance = 1e-7;
94 const double DEFAULT_DEVIATION_COEFFICIENT = 1.e-4;
95
96 //#define DEBUG_ACTIVATE_WINDOW
97 //#define DEBUG_SET_FOCUS
98
99 #ifdef WIN32
100 # define FSEP "\\"
101 #else
102 # define FSEP "/"
103 #endif
104
105 namespace ModuleBase_Tools {
106
107 //******************************************************************
108
109 //******************************************************************
110
111 void adjustMargins(QWidget* theWidget)
112 {
113   if(!theWidget)
114     return;
115   adjustMargins(theWidget->layout());
116 }
117
118 void adjustMargins(QLayout* theLayout)
119 {
120   if(!theLayout)
121     return;
122   theLayout->setContentsMargins(2, 5, 2, 5);
123   theLayout->setSpacing(4);
124 }
125
126 void zeroMargins(QWidget* theWidget)
127 {
128   if(!theWidget)
129     return;
130   zeroMargins(theWidget->layout());
131 }
132
133 void zeroMargins(QLayout* theLayout)
134 {
135   if(!theLayout)
136     return;
137   theLayout->setContentsMargins(0, 0, 0, 0);
138   theLayout->setSpacing(5);
139 }
140
141 void activateWindow(QWidget* theWidget, const QString& theInfo)
142 {
143   if (theWidget) {
144     theWidget->activateWindow();
145     theWidget->raise();
146   }
147
148 #ifdef DEBUG_ACTIVATE_WINDOW
149   qDebug(QString("activateWindow: %1").arg(theInfo).toStdString().c_str());
150 #endif
151 }
152
153 void setFocus(QWidget* theWidget, const QString& theInfo)
154 {
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     FieldStepPtr aStep = std::dynamic_pointer_cast<ModelAPI_ResultField::ModelAPI_FieldStep>(aObj);
401
402     hasResult |= ((aResult.get() != NULL) || (aStep.get() != NULL));
403     hasFeature |= (aFeature.get() != NULL);
404     hasFolder |= (aFolder.get() != NULL);
405     hasParameter |= (aConstruction.get() != NULL);
406     if (hasFeature)
407       hasCompositeOwner |= (ModelAPI_Tools::compositeOwner(aFeature) != NULL);
408
409     if (!hasResultInHistory && aResult.get()) {
410       FeaturePtr aFeature = ModelAPI_Feature::feature(aResult);
411       hasResultInHistory = aFeature.get() && aFeature->isInHistory();
412     }
413
414     if (hasFeature && hasResult  && hasParameter && hasCompositeOwner && hasFeature)
415       break;
416   }
417 }
418
419 /*bool setDefaultDeviationCoefficient(std::shared_ptr<GeomAPI_Shape> theGeomShape)
420 {
421   if (!theGeomShape.get())
422     return false;
423   // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
424   // correction of deviation for them should not influence to the application performance
425   GeomAPI_ShapeExplorer anExp(theGeomShape, GeomAPI_Shape::FACE);
426   bool anEmpty = anExp.empty();
427   return !anExp.more();
428 }*/
429
430 /*void setDefaultDeviationCoefficient(const std::shared_ptr<ModelAPI_Result>& theResult,
431                                     const Handle(Prs3d_Drawer)& theDrawer)
432 {
433   if (!theResult.get())
434     return;
435   bool aUseDeviation = false;
436
437   std::string aResultGroup = theResult->groupName();
438   if (aResultGroup == ModelAPI_ResultConstruction::group())
439     aUseDeviation = true;
440   else if (aResultGroup == ModelAPI_ResultBody::group()) {
441     GeomShapePtr aGeomShape = theResult->shape();
442     if (aGeomShape.get())
443       aUseDeviation = setDefaultDeviationCoefficient(aGeomShape);
444   }
445   if (aUseDeviation)
446     theDrawer->SetDeviationCoefficient(DEFAULT_DEVIATION_COEFFICIENT);
447 }
448 */
449 void setDefaultDeviationCoefficient(const TopoDS_Shape& theShape,
450                                     const Handle(Prs3d_Drawer)& theDrawer)
451 {
452   if (theShape.IsNull())
453     return;
454
455   std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape());
456   aGeomShape->setImpl(new TopoDS_Shape(theShape));
457
458   // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
459   // correction of deviation for them should not influence to the application performance
460   GeomAPI_ShapeExplorer anExp(aGeomShape, GeomAPI_Shape::FACE);
461   bool isConstruction = !anExp.more();
462
463   double aDeflection;
464   if (isConstruction)
465     aDeflection = Config_PropManager::real("Visualization", "construction_deflection");
466   else
467     aDeflection = Config_PropManager::real("Visualization", "body_deflection");
468
469   theDrawer->SetDeviationCoefficient(aDeflection);
470 }
471
472 Quantity_Color color(const std::string& theSection,
473                      const std::string& theName)
474 {
475   std::vector<int> aColor = Config_PropManager::color(theSection, theName);
476   return Quantity_Color(aColor[0] / 255., aColor[1] / 255., aColor[2] / 255., Quantity_TOC_RGB);
477 }
478
479 ObjectPtr getObject(const AttributePtr& theAttribute)
480 {
481   ObjectPtr anObject;
482   std::string anAttrType = theAttribute->attributeType();
483   if (anAttrType == ModelAPI_AttributeRefAttr::typeId()) {
484     AttributeRefAttrPtr anAttr =
485       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
486     if (anAttr != NULL && anAttr->isObject())
487       anObject = anAttr->object();
488   }
489   if (anAttrType == ModelAPI_AttributeSelection::typeId()) {
490     AttributeSelectionPtr anAttr =
491       std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
492     if (anAttr != NULL)
493       anObject = anAttr->context();
494   }
495   if (anAttrType == ModelAPI_AttributeReference::typeId()) {
496     AttributeReferencePtr anAttr =
497       std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
498     if (anAttr.get() != NULL)
499       anObject = anAttr->value();
500   }
501   return anObject;
502 }
503
504 TopAbs_ShapeEnum getCompoundSubType(const TopoDS_Shape& theShape)
505 {
506   TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
507
508   // for compounds check sub-shapes: it may be compound of needed type:
509   // Booleans may produce compounds of Solids
510   if (aShapeType == TopAbs_COMPOUND) {
511     for(TopoDS_Iterator aSubs(theShape); aSubs.More(); aSubs.Next()) {
512       if (!aSubs.Value().IsNull()) {
513         TopAbs_ShapeEnum aSubType = aSubs.Value().ShapeType();
514         if (aSubType == TopAbs_COMPOUND) { // compound of compound(s)
515           aShapeType = TopAbs_COMPOUND;
516           break;
517         }
518         if (aShapeType == TopAbs_COMPOUND) {
519           aShapeType = aSubType;
520         } else if (aShapeType != aSubType) { // compound of shapes of different types
521           aShapeType = TopAbs_COMPOUND;
522           break;
523         }
524       }
525     }
526   }
527   return aShapeType;
528 }
529
530 TopoDS_Shape getSelectedShape(const std::shared_ptr<ModuleBase_ViewerPrs>& thePrs)
531 {
532   if (thePrs->shape().get())
533     return thePrs->shape()->impl<TopoDS_Shape>();
534
535   Handle(StdSelect_BRepOwner) anOwner = Handle(StdSelect_BRepOwner)::DownCast(thePrs->owner());
536   if (!anOwner.IsNull())
537     return anOwner->Shape();
538
539   return TopoDS_Shape();
540 }
541
542 void getParameters(QStringList& theParameters)
543 {
544   theParameters.clear();
545
546   SessionPtr aSession = ModelAPI_Session::get();
547   std::list<DocumentPtr> aDocList;
548   DocumentPtr anActiveDocument = aSession->activeDocument();
549   DocumentPtr aRootDocument = aSession->moduleDocument();
550   aDocList.push_back(anActiveDocument);
551   if (anActiveDocument != aRootDocument) {
552     aDocList.push_back(aRootDocument);
553   }
554   std::string aGroupId = ModelAPI_ResultParameter::group();
555   for(std::list<DocumentPtr>::const_iterator it = aDocList.begin(); it != aDocList.end(); ++it) {
556     DocumentPtr aDocument = *it;
557     int aSize = aDocument->size(aGroupId);
558     for (int i = 0; i < aSize; i++) {
559       ObjectPtr anObject = aDocument->object(aGroupId, i);
560       std::string aParameterName = anObject->data()->name();
561       theParameters.append(aParameterName.c_str());
562     }
563   }
564 }
565
566 std::string findGreedAttribute(ModuleBase_IWorkshop* theWorkshop,
567                                const FeaturePtr& theFeature)
568 {
569   std::string anAttributeId;
570
571   std::string aXmlCfg, aDescription;
572   theWorkshop->module()->getXMLRepresentation(theFeature->getKind(), aXmlCfg, aDescription);
573
574   ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
575   std::string anAttributeTitle;
576   aFactory.getGreedAttribute(anAttributeId);
577
578   return anAttributeId;
579 }
580
581 bool hasObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
582                const std::shared_ptr<GeomAPI_Shape>& theShape,
583                ModuleBase_IWorkshop* theWorkshop,
584                const bool theTemporarily)
585 {
586   bool aHasObject = false;
587   if (!theAttribute.get())
588     return aHasObject;
589
590   std::string aType = theAttribute->attributeType();
591   if (aType == ModelAPI_AttributeReference::typeId()) {
592     AttributeReferencePtr aRef =
593       std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
594     ObjectPtr aObject = aRef->value();
595     aHasObject = aObject && aObject->isSame(theObject);
596     //if (!(aObject && aObject->isSame(theObject))) {
597     //  aRef->setValue(theObject);
598     //}
599   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
600     AttributeRefAttrPtr aRefAttr =
601       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
602
603     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
604     if (anAttribute.get()) {
605       //aRefAttr->setAttr(anAttribute);
606     }
607     else {
608       ObjectPtr aObject = aRefAttr->object();
609       aHasObject = aObject && aObject->isSame(theObject);
610       //if (!(aObject && aObject->isSame(theObject))) {
611       //  aRefAttr->setObject(theObject);
612       //}
613     }
614   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
615     /*AttributeSelectionPtr aSelectAttr =
616                              std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
617     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
618     if (aSelectAttr.get() != NULL) {
619       aSelectAttr->setValue(aResult, theShape, theTemporarily);
620     }*/
621   }
622   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
623     AttributeSelectionListPtr aSelectionListAttr =
624                          std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
625     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
626     aHasObject = aSelectionListAttr->isInList(aResult, theShape, theTemporarily);
627   }
628   else if (aType == ModelAPI_AttributeRefList::typeId()) {
629     AttributeRefListPtr aRefListAttr =
630       std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
631     aHasObject = aRefListAttr->isInList(theObject);
632     //if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject))
633     //  aRefListAttr->append(theObject);
634   }
635   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
636     AttributeRefAttrListPtr aRefAttrListAttr =
637       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
638     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
639
640     if (anAttribute.get()) {
641       aHasObject = aRefAttrListAttr->isInList(anAttribute);
642       //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
643       //  aRefAttrListAttr->append(anAttribute);
644     }
645     else {
646       aHasObject = aRefAttrListAttr->isInList(theObject);
647       //if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject))
648       //  aRefAttrListAttr->append(theObject);
649     }
650   }
651   return aHasObject;
652 }
653
654 bool setObject(const AttributePtr& theAttribute, const ObjectPtr& theObject,
655                const GeomShapePtr& theShape, ModuleBase_IWorkshop* theWorkshop,
656                const bool theTemporarily, const bool theCheckIfAttributeHasObject)
657 {
658   if (!theAttribute.get())
659     return false;
660
661   bool isDone = true;
662   std::string aType = theAttribute->attributeType();
663   if (aType == ModelAPI_AttributeReference::typeId()) {
664     AttributeReferencePtr aRef =
665       std::dynamic_pointer_cast<ModelAPI_AttributeReference>(theAttribute);
666     ObjectPtr aObject = aRef->value();
667     if (!(aObject && aObject->isSame(theObject))) {
668       aRef->setValue(theObject);
669     }
670   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
671     AttributeRefAttrPtr aRefAttr =
672       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
673
674     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
675     if (anAttribute.get())
676       aRefAttr->setAttr(anAttribute);
677     else {
678       ObjectPtr aObject = aRefAttr->object();
679       if (!(aObject && aObject->isSame(theObject))) {
680         aRefAttr->setObject(theObject);
681       }
682     }
683   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
684     AttributeSelectionPtr aSelectAttr =
685                              std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(theAttribute);
686     if (aSelectAttr.get() != NULL) {
687       aSelectAttr->setValue(theObject, theShape, theTemporarily);
688     }
689   }
690   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
691     AttributeSelectionListPtr aSelectionListAttr =
692                          std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
693     if (!theCheckIfAttributeHasObject ||
694       !aSelectionListAttr->isInList(theObject, theShape, theTemporarily))
695       aSelectionListAttr->append(theObject, theShape, theTemporarily);
696   }
697   else if (aType == ModelAPI_AttributeRefList::typeId()) {
698     AttributeRefListPtr aRefListAttr =
699       std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
700     if (!theCheckIfAttributeHasObject || !aRefListAttr->isInList(theObject)) {
701       if (theObject.get())
702         aRefListAttr->append(theObject);
703       else
704         isDone = false;
705     }
706   }
707   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
708     AttributeRefAttrListPtr aRefAttrListAttr =
709       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(theAttribute);
710     AttributePtr anAttribute = theWorkshop->module()->findAttribute(theObject, theShape);
711
712     if (anAttribute.get()) {
713       if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(anAttribute))
714         aRefAttrListAttr->append(anAttribute);
715     }
716     else {
717       if (!theCheckIfAttributeHasObject || !aRefAttrListAttr->isInList(theObject)) {
718         if (theObject.get())
719           aRefAttrListAttr->append(theObject);
720         else
721           isDone = false;
722       }
723     }
724   }
725   return isDone;
726 }
727
728 GeomShapePtr getShape(const AttributePtr& theAttribute, ModuleBase_IWorkshop* theWorkshop)
729 {
730   GeomShapePtr aShape;
731   if (!theAttribute.get())
732     return aShape;
733
734   std::string aType = theAttribute->attributeType();
735   if (aType == ModelAPI_AttributeReference::typeId()) {
736   } else if (aType == ModelAPI_AttributeRefAttr::typeId()) {
737     AttributeRefAttrPtr aRefAttr =
738       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
739     if (aRefAttr.get() && !aRefAttr->isObject()) {
740       AttributePtr anAttribute = aRefAttr->attr();
741       aShape = theWorkshop->module()->findShape(anAttribute);
742     }
743   } else if (aType == ModelAPI_AttributeSelection::typeId()) {
744     AttributeSelectionPtr aSelectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>
745                                                                                  (theAttribute);
746     aShape = aSelectAttr->value();
747   }
748   else // Geom2D point processing
749     aShape = theWorkshop->module()->findShape(theAttribute);
750   return aShape;
751 }
752
753 void flushUpdated(ObjectPtr theObject)
754 {
755   blockUpdateViewer(true);
756
757   // Fix the problem of not previewed results of constraints applied. Flush Create/Delete
758   // (for the sketch result) to start processing of the sketch in the solver.
759   // TODO: these flushes should be moved in a separate method provided by Model
760   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
761   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
762   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
763
764   blockUpdateViewer(false);
765 }
766
767 void blockUpdateViewer(const bool theValue)
768 {
769   // the viewer update should be blocked in order to avoid the temporary feature content
770   // when the solver processes the feature, the redisplay message can be flushed
771   // what caused the display in the viewer preliminary states of object
772   // e.g. fillet feature, angle value change
773   std::shared_ptr<Events_Message> aMsg;
774   if (theValue) {
775     aMsg = std::shared_ptr<Events_Message>(
776         new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)));
777   }
778   else {
779     // the viewer update should be unblocked
780     aMsg = std::shared_ptr<Events_Message>(
781         new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)));
782   }
783   Events_Loop::loop()->send(aMsg);
784 }
785
786 QString wrapTextByWords(const QString& theValue, QWidget* theWidget,
787                                           int theMaxLineInPixels)
788 {
789   static QFontMetrics tfm(theWidget ? theWidget->font() : QApplication::font());
790   static qreal phi = 2.618;
791
792   QRect aBounds = tfm.boundingRect(theValue);
793   if(aBounds.width() <= theMaxLineInPixels)
794     return theValue;
795
796   qreal s = aBounds.width() * aBounds.height();
797   qreal aGoldWidth = sqrt(s*phi);
798
799   QStringList aWords = theValue.split(" ", QString::SkipEmptyParts);
800   QStringList aLines;
801   int n = aWords.count();
802   QString aLine;
803   for (int i = 0; i < n; i++) {
804     QString aLineExt =  i == 0 ? aWords[i] : aLine + " " + aWords[i];
805     qreal anWidthNonExt = tfm.boundingRect(aLine).width();
806     qreal anWidthExt = tfm.boundingRect(aLineExt).width();
807     qreal aDeltaNonExt = fabs(anWidthNonExt-aGoldWidth);
808     qreal aDeltaExt    = fabs(anWidthExt-aGoldWidth);
809     if(aDeltaNonExt < aDeltaExt) {
810       // new line
811       aLines.append(aLine);
812       aLine = aWords[i];
813     }
814     else
815       aLine = aLineExt;
816   }
817
818   if(!aLine.isEmpty())
819     aLines.append(aLine);
820
821   QString aResult = aLines.join("\n");
822   return aResult;
823 }
824
825 //**************************************************************
826 QLocale doubleLocale()
827 {
828   // VSR 01/07/2010: Disable thousands separator for spin box
829   // (to avoid inconsistency of double-2-string and string-2-double conversion)
830   QLocale aLocale;
831   aLocale.setNumberOptions(aLocale.numberOptions() |
832                            QLocale::OmitGroupSeparator |
833                            QLocale::RejectGroupSeparator);
834   return aLocale;
835 }
836
837 //**************************************************************
838 void refsToFeatureInFeatureDocument(const ObjectPtr& theObject,
839                                     std::set<FeaturePtr>& theRefFeatures)
840 {
841   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
842   if (aFeature.get()) {
843     DocumentPtr aFeatureDoc = aFeature->document();
844     // 1. find references in the current document
845     aFeatureDoc->refsToFeature(aFeature, theRefFeatures, false);
846   }
847 }
848
849
850 //**************************************************************
851 /*bool isSubOfComposite(const ObjectPtr& theObject)
852 {
853   bool isSub = false;
854   std::set<FeaturePtr> aRefFeatures;
855   refsToFeatureInFeatureDocument(theObject, aRefFeatures);
856   std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
857                                        aLast = aRefFeatures.end();
858   for (; anIt != aLast && !isSub; anIt++) {
859     isSub = isSubOfComposite(theObject, *anIt);
860   }
861   return isSub;
862 }*/
863
864 //**************************************************************
865 /*bool isSubOfComposite(const ObjectPtr& theObject, const FeaturePtr& theFeature)
866 {
867   bool isSub = false;
868   CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
869   if (aComposite.get()) {
870     isSub = aComposite->isSub(theObject);
871     // the recursive is possible, the parameters are sketch circle and extrusion cut. They are
872     // separated by composite sketch feature
873     if (!isSub) {
874       int aNbSubs = aComposite->numberOfSubs();
875       for (int aSub = 0; aSub < aNbSubs && !isSub; aSub++) {
876         isSub = isSubOfComposite(theObject, aComposite->subFeature(aSub));
877       }
878     }
879   }
880   return isSub;
881 }*/
882
883 //**************************************************************
884 ResultPtr firstResult(const ObjectPtr& theObject)
885 {
886   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
887   if (!aResult.get()) {
888     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
889     if (aFeature.get())
890       aResult = aFeature->firstResult();
891   }
892   return aResult;
893 }
894
895 //**************************************************************
896 bool isFeatureOfResult(const FeaturePtr& theFeature, const std::string& theGroupOfResult)
897 {
898   bool isResult = false;
899
900   if (!theFeature->data()->isValid())
901     return isResult;
902
903   ResultPtr aFirstResult = theFeature->firstResult();
904   if (!aFirstResult.get())
905     return isResult;
906
907   return aFirstResult->groupName() == theGroupOfResult;
908 }
909
910 //**************************************************************
911 bool hasModuleDocumentFeature(const std::set<FeaturePtr>& theFeatures)
912 {
913   bool aFoundModuleDocumentObject = false;
914   DocumentPtr aModuleDoc = ModelAPI_Session::get()->moduleDocument();
915
916   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(), aLast = theFeatures.end();
917   for (; anIt != aLast && !aFoundModuleDocumentObject; anIt++) {
918     FeaturePtr aFeature = *anIt;
919     ResultPtr aResult = ModuleBase_Tools::firstResult(aFeature);
920     if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group())
921       continue;
922     aFoundModuleDocumentObject = aFeature->document() == aModuleDoc;
923   }
924
925   return aFoundModuleDocumentObject;
926 }
927
928 //**************************************************************
929 bool askToDelete(const std::set<FeaturePtr> theFeatures,
930                  const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
931                  QWidget* theParent,
932                  std::set<FeaturePtr>& theReferencesToDelete,
933                  const std::string& thePrefixInfo)
934 {
935   QString aNotActivatedDocWrn;
936   std::string aNotActivatedNames;
937   if (!ModelAPI_Tools::allDocumentsActivated(aNotActivatedNames)) {
938     if (ModuleBase_Tools::hasModuleDocumentFeature(theFeatures))
939       aNotActivatedDocWrn =
940         QObject::tr("Selected objects can be used in Part documents which are not loaded:%1.\n")
941                             .arg(aNotActivatedNames.c_str());
942   }
943
944   std::set<FeaturePtr> aFeaturesRefsTo;
945   std::set<FeaturePtr> aFeaturesRefsToParameter;
946   std::set<FeaturePtr> aParameterFeatures;
947   QStringList aPartFeatureNames;
948   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
949                                        aLast = theFeatures.end();
950   // separate features to references to parameter features and references to others
951   for (; anIt != aLast; anIt++) {
952     FeaturePtr aFeature = *anIt;
953     if (theReferences.find(aFeature) == theReferences.end())
954       continue;
955
956     if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
957       aPartFeatureNames.append(aFeature->name().c_str());
958
959     std::set<FeaturePtr> aRefFeatures;
960     std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
961     std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
962     for (; aRefIt != aRefLast; aRefIt++) {
963       FeaturePtr aRefFeature = *aRefIt;
964       if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
965           aRefFeatures.find(aRefFeature) == aRefFeatures.end()) // it is not added
966         aRefFeatures.insert(aRefFeature);
967     }
968
969     if (isFeatureOfResult(aFeature, ModelAPI_ResultParameter::group())) {
970       aFeaturesRefsToParameter.insert(aRefFeatures.begin(), aRefFeatures.end());
971       aParameterFeatures.insert(aFeature);
972     }
973     else {
974       theReferencesToDelete.insert(aRefFeatures.begin(), aRefFeatures.end());
975     }
976   }
977
978   std::set<FeaturePtr> aFeaturesRefsToParameterOnly;
979   anIt = aFeaturesRefsToParameter.begin();
980   aLast = aFeaturesRefsToParameter.end();
981   // separate features to references to parameter features and references to others
982   QStringList aParamFeatureNames;
983   for (; anIt != aLast; anIt++) {
984     FeaturePtr aFeature = *anIt;
985     if (theReferencesToDelete.find(aFeature) == theReferencesToDelete.end()) {
986       aFeaturesRefsToParameterOnly.insert(aFeature);
987       aParamFeatureNames.append(aFeature->name().c_str());
988     }
989   }
990   aParamFeatureNames.sort();
991   QStringList anOtherFeatureNames;
992   anIt = theReferencesToDelete.begin();
993   aLast = theReferencesToDelete.end();
994   for (; anIt != aLast; anIt++) {
995     FeaturePtr aFeature = *anIt;
996     if (aFeature->getKind() == "RemoveResults")
997       continue; // skip the remove results feature mentioning: result will be removed anyway
998     if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
999       aPartFeatureNames.append(aFeature->name().c_str());
1000     else
1001       anOtherFeatureNames.append(aFeature->name().c_str());
1002   }
1003   aPartFeatureNames.sort();
1004   anOtherFeatureNames.sort();
1005
1006   bool aCanReplaceParameters = !aFeaturesRefsToParameterOnly.empty();
1007
1008   QMessageBox aMessageBox(theParent);
1009   aMessageBox.setWindowTitle(QObject::tr("Delete features"));
1010   aMessageBox.setIcon(QMessageBox::Warning);
1011   aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1012   aMessageBox.setDefaultButton(QMessageBox::No);
1013
1014   QString aText;
1015   if (!thePrefixInfo.empty())
1016     aText = thePrefixInfo.c_str();
1017   QString aSep = ", ";
1018   if (!aPartFeatureNames.empty()) {
1019     aText += QString(QObject::tr("The following parts will be deleted: %1.\n"))
1020              .arg(aPartFeatureNames.join(aSep));
1021   }
1022   if (!aNotActivatedDocWrn.isEmpty())
1023     aText += aNotActivatedDocWrn;
1024   if (!anOtherFeatureNames.empty()) {
1025     const char* aMsg = "Features are used in the following features: %1.\nThese "
1026                        "features will be deleted.\n";
1027     aText += QString(QObject::tr(aMsg))
1028                      .arg(anOtherFeatureNames.join(aSep));
1029   }
1030   if (!aParamFeatureNames.empty()) {
1031     const char* aMsg = "Parameters are used directly and through a sequence "
1032                        "of dependencies in the following features: %1.\nThese features will "
1033                        "be deleted.\nOr parameters could be replaced by their values.\n";
1034     aText += QString(QObject::tr(aMsg))
1035                      .arg(aParamFeatureNames.join(aSep));
1036     QPushButton *aReplaceButton =
1037       aMessageBox.addButton(QObject::tr("Replace"), QMessageBox::ActionRole);
1038   }
1039
1040   if (!aText.isEmpty()) {
1041     aText += "Would you like to continue?";
1042     aMessageBox.setText(aText);
1043     aMessageBox.exec();
1044     QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1045
1046     if (aButtonRole == QMessageBox::NoRole)
1047       return false;
1048
1049     if (aButtonRole == QMessageBox::ActionRole) {
1050       foreach (FeaturePtr aObj, aParameterFeatures)
1051         ModelAPI_ReplaceParameterMessage::send(aObj, 0);
1052     }
1053     else
1054       theReferencesToDelete.insert(aFeaturesRefsToParameterOnly.begin(),
1055                                    aFeaturesRefsToParameterOnly.end());
1056   }
1057   return true;
1058 }
1059
1060 //**************************************************************
1061 void convertToFeatures(const QObjectPtrList& theObjects, std::set<FeaturePtr>& theFeatures)
1062 {
1063   QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1064   for(; anIt != aLast; anIt++) {
1065     ObjectPtr anObject = *anIt;
1066     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1067     // for parameter result, use the corresponded reature to be removed
1068     if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1069       aFeature = ModelAPI_Feature::feature(anObject);
1070     }
1071     if (aFeature.get())
1072       theFeatures.insert(aFeature);
1073   }
1074 }
1075
1076 //**************************************************************
1077 void convertToFolders(const QObjectPtrList& theObjects,
1078                                          std::set<FolderPtr>& theFolders)
1079 {
1080   QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1081   for(; anIt != aLast; anIt++) {
1082     ObjectPtr anObject = *anIt;
1083     FolderPtr aFeature = std::dynamic_pointer_cast<ModelAPI_Folder>(anObject);
1084     if (aFeature.get())
1085       theFolders.insert(aFeature);
1086   }
1087 }
1088
1089
1090 //**************************************************************
1091 QString translate(const Events_InfoMessage& theMessage)
1092 {
1093   QString aMessage;
1094
1095   if (!theMessage.empty()) {
1096     std::string aStr = Config_Translator::translate(theMessage);
1097     if (!aStr.empty()) {
1098       std::string aCodec = Config_Translator::codec(theMessage);
1099       aMessage = QTextCodec::codecForName(aCodec.c_str())->toUnicode(aStr.c_str());
1100     }
1101   }
1102
1103   return aMessage;
1104 }
1105
1106 QString translate(const std::string& theContext, const std::string& theMessage)
1107 {
1108   QString aMessage;
1109
1110   if (!theMessage.empty()) {
1111     std::string aStr = Config_Translator::translate(theContext, theMessage);
1112     if (!aStr.empty()) {
1113       std::string aCodec = Config_Translator::codec(theContext);
1114       aMessage = QTextCodec::codecForName(aCodec.c_str())->toUnicode(aStr.c_str());
1115     }
1116   }
1117
1118   return aMessage;
1119 }
1120
1121 void setPointBallHighlighting(AIS_Shape* theAIS)
1122 {
1123   static Handle(Image_AlienPixMap) aPixMap;
1124   if(aPixMap.IsNull()) {
1125     // Load icon for the presentation
1126     std::string aFile;
1127     char* anEnv = getenv("SHAPER_ROOT_DIR");
1128     if(anEnv) {
1129       aFile = std::string(anEnv) +
1130         FSEP + "share" + FSEP + "salome" + FSEP + "resources" + FSEP + "shaper";
1131     } else {
1132       anEnv = getenv("CADBUILDER_ROOT_DIR");
1133       if (anEnv)
1134         aFile = std::string(anEnv) + FSEP + "resources";
1135     }
1136
1137     aFile += FSEP;
1138     static const std::string aMarkerName = "marker_dot.png";
1139     aFile += aMarkerName;
1140     aPixMap = new Image_AlienPixMap();
1141     if(!aPixMap->Load(aFile.c_str())) {
1142       // The icon for constraint is not found
1143       static const std::string aMsg =
1144         "Error: Point market not found by path: \"" + aFile + "\". Falling back.";
1145       //Events_InfoMessage("ModuleBase_Tools::setPointBallHighlighting", aMsg).send();
1146     }
1147   }
1148
1149   Handle(Graphic3d_AspectMarker3d) anAspect;
1150   Handle(Prs3d_Drawer) aDrawer = theAIS->DynamicHilightAttributes();
1151   if (aDrawer.IsNull()) {
1152     if (ModuleBase_IViewer::DefaultHighlightDrawer.IsNull())
1153       return;
1154     aDrawer = new Prs3d_Drawer(*ModuleBase_IViewer::DefaultHighlightDrawer);
1155     if (!aDrawer->HasOwnPointAspect()) {
1156       aDrawer->SetPointAspect(new Prs3d_PointAspect(Aspect_TOM_BALL, Quantity_NOC_BLACK, 2.0));
1157     }
1158   }
1159   if(aDrawer->HasOwnPointAspect()) {
1160     Handle(Prs3d_PointAspect) aPntAspect = aDrawer->PointAspect();
1161     if(aPixMap->IsEmpty()) {
1162       anAspect = aPntAspect->Aspect();
1163       anAspect->SetType(Aspect_TOM_BALL);
1164     } else {
1165       if(aPixMap->Format() == Image_PixMap::ImgGray) {
1166         aPixMap->SetFormat (Image_PixMap::ImgAlpha);
1167       } else if(aPixMap->Format() == Image_PixMap::ImgGrayF) {
1168         aPixMap->SetFormat (Image_PixMap::ImgAlphaF);
1169       }
1170       anAspect = new Graphic3d_AspectMarker3d(aPixMap);
1171       aPntAspect->SetAspect(anAspect);
1172     }
1173     aDrawer->SetPointAspect(aPntAspect);
1174           theAIS->SetDynamicHilightAttributes(aDrawer);
1175   }
1176 }
1177
1178 FeaturePtr createParameter(const QString& theText)
1179 {
1180   FeaturePtr aParameter;
1181   QStringList aList = theText.split("=");
1182   if (aList.count() != 2) {
1183     return aParameter;
1184   }
1185   QString aParamName = aList.at(0).trimmed();
1186
1187   if (isNameExist(aParamName, FeaturePtr())) {
1188     return aParameter;
1189   }
1190
1191   if (!ModelAPI_Expression::isVariable(aParamName.toStdString())) {
1192     return aParameter;
1193   }
1194
1195   QString aExpression = aList.at(1).trimmed();
1196   if (aExpression.isEmpty()) {
1197     return aParameter;
1198   }
1199
1200   SessionPtr aMgr = ModelAPI_Session::get();
1201   std::shared_ptr<ModelAPI_Document> aDoc = aMgr->activeDocument();
1202
1203   aParameter = aDoc->addFeature("Parameter");
1204   if (aParameter.get()) {
1205     AttributeStringPtr aNameAttr = aParameter->string("variable");
1206     aNameAttr->setValue(aParamName.toStdString());
1207
1208     AttributeStringPtr aExprAttr = aParameter->string("expression");
1209     aExprAttr->setValue(aExpression.toStdString());
1210     aParameter->execute();
1211
1212     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1213     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
1214   }
1215   return aParameter;
1216 }
1217
1218 void editParameter(FeaturePtr theParam, const QString& theText)
1219 {
1220   QStringList aList = theText.split("=");
1221   QString aParamName = aList.at(0).trimmed();
1222
1223   QString aExpression = aList.at(1).trimmed();
1224   if (aExpression.isEmpty()) {
1225     return;
1226   }
1227
1228   if (isNameExist(aParamName, theParam)) {
1229     return;
1230   }
1231   AttributeStringPtr aNameAttr = theParam->string("variable");
1232   aNameAttr->setValue(aParamName.toStdString());
1233
1234   AttributeStringPtr aExprAttr = theParam->string("expression");
1235   aExprAttr->setValue(aExpression.toStdString());
1236   theParam->execute();
1237
1238   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
1239 }
1240
1241 bool isNameExist(const QString& theName, FeaturePtr theIgnoreParameter)
1242 {
1243   SessionPtr aMgr = ModelAPI_Session::get();
1244   std::shared_ptr<ModelAPI_Document> aDoc = aMgr->activeDocument();
1245   FeaturePtr aParamFeature;
1246   int aNbFeatures = aDoc->numInternalFeatures();
1247   std::string aName = theName.toStdString();
1248   for (int i = 0; i < aNbFeatures; i++) {
1249     aParamFeature = aDoc->internalFeature(i);
1250     if (aParamFeature && aParamFeature->getKind() == "Parameter") {
1251       if ((theIgnoreParameter != aParamFeature) && (aParamFeature->name() == aName))
1252         return true;
1253     }
1254   }
1255   return false;
1256 }
1257
1258 FeaturePtr findParameter(const QString& theName)
1259 {
1260   SessionPtr aMgr = ModelAPI_Session::get();
1261   std::shared_ptr<ModelAPI_Document> aDoc = aMgr->activeDocument();
1262   FeaturePtr aParamFeature;
1263   int aNbFeatures = aDoc->numInternalFeatures();
1264   std::string aName = theName.toStdString();
1265   for (int i = 0; i < aNbFeatures; i++) {
1266     aParamFeature = aDoc->internalFeature(i);
1267     if (aParamFeature && aParamFeature->getKind() == "Parameter") {
1268       if (aParamFeature->name() == aName)
1269         return aParamFeature;
1270     }
1271   }
1272   return FeaturePtr();
1273 }
1274
1275
1276 //********************************************************************
1277 std::string generateName(const AttributePtr& theAttribute,
1278   ModuleBase_IWorkshop* theWorkshop)
1279 {
1280   std::string aName;
1281   if (theAttribute.get() != NULL) {
1282     ModuleBase_Operation* anOperation = theWorkshop->currentOperation();
1283
1284     FeaturePtr aFeature = ModelAPI_Feature::feature(theAttribute->owner());
1285     if (aFeature.get()) {
1286       std::string aXmlCfg, aDescription;
1287       theWorkshop->module()->getXMLRepresentation(aFeature->getKind(), aXmlCfg, aDescription);
1288
1289       ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
1290       std::string anAttributeTitle;
1291       aFactory.getAttributeTitle(theAttribute->id(), anAttributeTitle);
1292
1293       std::stringstream aStreamName;
1294       aStreamName << theAttribute->owner()->data()->name() << "/" << anAttributeTitle.c_str();
1295       aName = aStreamName.str();
1296     }
1297   }
1298   return aName;
1299 }
1300
1301 bool isSameShape(const TopoDS_Shape& theShape1, const TopoDS_Shape& theShape2)
1302 {
1303   // In case of compound we cannot rely on simple comparison method.
1304   // If the compound is generated by Group feature then this compound is alwais new.
1305   // So, we have to compare content of these compounds
1306   if (theShape1.ShapeType() != theShape2.ShapeType())
1307     return false;
1308
1309   if (theShape1.ShapeType() != TopAbs_COMPOUND)
1310     return theShape1.IsSame(theShape2);
1311
1312   TopoDS_Iterator aIt1(theShape1);
1313   TopoDS_Iterator aIt2(theShape2);
1314
1315   for (; aIt1.More() && aIt2.More(); aIt1.Next(), aIt2.Next()) {
1316     if (!(aIt1.Value()).IsSame(aIt2.Value()))
1317       return false;
1318   }
1319   return true;
1320 }
1321
1322
1323 } // namespace ModuleBase_Tools
1324
1325