Salome HOME
Initial implementation of restoreByName selector method
[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_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   activateWindow(theWidget);
156   theWidget->setFocus();
157   // rectangle of focus is not visible on tool button widgets
158   theWidget->repaint();
159 #ifdef DEBUG_SET_FOCUS
160   qDebug(QString("setFocus: %1").arg(theInfo).toStdString().c_str());
161 #endif
162 }
163
164 void setShadowEffect(QWidget* theWidget, const bool isSetEffect)
165 {
166   if (isSetEffect) {
167     QGraphicsDropShadowEffect* aGlowEffect = new QGraphicsDropShadowEffect();
168     aGlowEffect->setOffset(.0);
169     aGlowEffect->setBlurRadius(10.0);
170     aGlowEffect->setColor(QColor(0, 170, 255)); // Light-blue color, #00AAFF
171     theWidget->setGraphicsEffect(aGlowEffect);
172   }
173   else {
174     QGraphicsEffect* anEffect = theWidget->graphicsEffect();
175     if(anEffect)
176       anEffect->deleteLater();
177     theWidget->setGraphicsEffect(NULL);
178   }
179 }
180
181 QPixmap composite(const QString& theAdditionalIcon, const QString& theIcon)
182 {
183   QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
184   QImage anAditional(theAdditionalIcon);
185   return composite(anAditional, anIcon);
186 }
187
188 QPixmap composite(const QImage& theAdditionalIcon, QImage& theIcon)
189 {
190   if (theIcon.isNull())
191     return QPixmap();
192
193   int anAddWidth = theAdditionalIcon.width();
194   int anAddHeight = theAdditionalIcon.height();
195
196   int aWidth = theIcon.width();
197   int aHeight = theIcon.height();
198
199   int aStartWidthPos = aWidth - anAddWidth;
200   int aStartHeightPos = aHeight - anAddHeight;
201
202   for (int i = 0; i < anAddWidth && i + aStartWidthPos < aWidth; i++)
203   {
204     for (int j = 0; j < anAddHeight && j + aStartHeightPos < aHeight; j++)
205     {
206       if (qAlpha(theAdditionalIcon.pixel(i, j)) > 0)
207         theIcon.setPixel(i + aStartWidthPos, j + aStartHeightPos, theAdditionalIcon.pixel(i, j));
208     }
209   }
210   return QPixmap::fromImage(theIcon);
211 }
212
213 QPixmap lighter(const QString& theIcon, const int theLighterValue)
214 {
215   QImage anIcon = ModuleBase_IconFactory::loadImage(theIcon);
216   if (anIcon.isNull())
217     return QPixmap();
218
219   QImage aResult = ModuleBase_IconFactory::loadImage(theIcon);
220   for (int i = 0; i < anIcon.width(); i++)
221   {
222     for (int j = 0; j < anIcon.height(); j++)
223     {
224       QRgb anRgb = anIcon.pixel(i, j);
225       QColor aPixelColor(qRed(anRgb), qGreen(anRgb), qBlue(anRgb),
226                          qAlpha(aResult.pixel(i, j)));
227
228       QColor aLighterColor = aPixelColor.lighter(theLighterValue);
229       aResult.setPixel(i, j, qRgba(aLighterColor.red(), aLighterColor.green(),
230                                     aLighterColor.blue(), aLighterColor.alpha()));
231     }
232   }
233   return QPixmap::fromImage(aResult);
234 }
235
236 void setSpinText(ModuleBase_ParamSpinBox* theSpin, const QString& theText)
237 {
238   if (theSpin->text() == theText)
239     return;
240   // In order to avoid extra text setting because it will
241   // reset cursor position in control
242   bool isBlocked = theSpin->blockSignals(true);
243   theSpin->setText(theText);
244   theSpin->blockSignals(isBlocked);
245 }
246
247 void setSpinValue(QDoubleSpinBox* theSpin, double theValue)
248 {
249   if (fabs(theSpin->value() - theValue) < tolerance)
250     return;
251   bool isBlocked = theSpin->blockSignals(true);
252   theSpin->setValue(theValue);
253   theSpin->blockSignals(isBlocked);
254 }
255
256 void setSpinValue(ModuleBase_ParamSpinBox* theSpin, double theValue)
257 {
258   if (fabs(theSpin->value() - theValue) < tolerance)
259     return;
260   bool isBlocked = theSpin->blockSignals(true);
261   theSpin->setValue(theValue);
262   theSpin->blockSignals(isBlocked);
263 }
264
265 void setSpinText(ModuleBase_ParamIntSpinBox* theSpin, const QString& theText)
266 {
267   // In order to avoid extra text setting because it will
268   // reset cursor position in control
269   if (theSpin->text() == theText)
270     return;
271   bool isBlocked = theSpin->blockSignals(true);
272   theSpin->setText(theText);
273   theSpin->blockSignals(isBlocked);
274 }
275
276 void setSpinValue(ModuleBase_ParamIntSpinBox* theSpin, int theValue)
277 {
278   if (theSpin->value() == theValue)
279     return;
280   bool isBlocked = theSpin->blockSignals(true);
281   theSpin->setValue(theValue);
282   theSpin->blockSignals(isBlocked);
283 }
284
285 QAction* createAction(const QIcon& theIcon, const QString& theText,
286                       QObject* theParent, const QObject* theReceiver,
287                       const char* theMember, const QString& theToolTip,
288                       const QString& theStatusTip)
289 {
290   QAction* anAction = new QAction(theIcon, theText, theParent);
291   anAction->setToolTip(theToolTip.isEmpty() ? theText : theToolTip);
292   anAction->setStatusTip(!theStatusTip.isEmpty() ? theStatusTip :
293                                                    (!theToolTip.isEmpty() ? theToolTip : theText));
294   if (theReceiver)
295     QObject::connect(anAction, SIGNAL(triggered(bool)), theReceiver, theMember);
296
297   return anAction;
298 }
299
300 #ifdef _DEBUG
301 QString objectName(const ObjectPtr& theObj)
302 {
303   if (!theObj.get())
304     return "";
305
306   return theObj->data()->name().c_str();
307 }
308
309 QString objectInfo(const ObjectPtr& theObj, const bool isUseAttributesInfo)
310 {
311   QString aFeatureStr = "feature";
312   if (!theObj.get())
313     return aFeatureStr;
314
315   std::ostringstream aPtrStr;
316   aPtrStr << "[" << theObj.get() << "]";
317
318   ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theObj);
319   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
320   if(aRes.get()) {
321     aFeatureStr.append(QString("(result%1)").arg(aPtrStr.str().c_str()).toStdString() .c_str());
322     if (aRes->isDisabled())
323       aFeatureStr.append("[disabled]");
324     if (aRes->isConcealed())
325       aFeatureStr.append("[concealed]");
326     if (ModelAPI_Tools::hasSubResults(aRes))
327       aFeatureStr.append("[hasSubResults]");
328
329     aFeature = ModelAPI_Feature::feature(aRes);
330   }
331   else
332     aFeatureStr.append(aPtrStr.str().c_str());
333
334   if (aFeature.get()) {
335     aFeatureStr.append(QString(": %1").arg(aFeature->getKind().c_str()).toStdString().c_str());
336     if (aFeature->data()->isValid()) {
337       aFeatureStr.append(QString(", name=%1").arg(theObj->data()->name().c_str()).toStdString()
338                                                                                        .c_str());
339     }
340     if (isUseAttributesInfo) {
341       std::set<std::shared_ptr<ModelAPI_Attribute> > anAttributes;
342       std::string aPointsInfo = ModelGeomAlgo_Point2D::getPontAttributesInfo(aFeature,
343                                                                           anAttributes).c_str();
344       if (!aPointsInfo.empty())
345         aFeatureStr.append(QString(", attributes: %1")
346           .arg(aPointsInfo.c_str()).toStdString().c_str());
347     }
348   }
349
350   return aFeatureStr;
351 }
352 #endif
353
354 typedef QMap<QString, int> ShapeTypes;
355 static ShapeTypes myShapeTypes;
356
357 int shapeType(const QString& theType)
358 {
359   if (myShapeTypes.count() == 0) {
360     myShapeTypes["compound"]   = TopAbs_COMPOUND;
361     myShapeTypes["compounds"]  = TopAbs_COMPOUND;
362     myShapeTypes["compsolid"]  = TopAbs_COMPSOLID;
363     myShapeTypes["compsolids"] = TopAbs_COMPSOLID;
364     myShapeTypes["solid"]      = TopAbs_SOLID;
365     myShapeTypes["solids"]     = TopAbs_SOLID;
366     myShapeTypes["shell"]      = TopAbs_SHELL;
367     myShapeTypes["shells"]     = TopAbs_SHELL;
368     myShapeTypes["face"]       = TopAbs_FACE;
369     myShapeTypes["faces"]      = TopAbs_FACE;
370     myShapeTypes["wire"]       = TopAbs_WIRE;
371     myShapeTypes["wires"]      = TopAbs_WIRE;
372     myShapeTypes["edge"]       = TopAbs_EDGE;
373     myShapeTypes["edges"]      = TopAbs_EDGE;
374     myShapeTypes["vertex"]     = TopAbs_VERTEX;
375     myShapeTypes["vertices"]   = TopAbs_VERTEX;
376     myShapeTypes["object"]     = ModuleBase_ResultPrs::Sel_Result;
377     myShapeTypes["objects"]    = ModuleBase_ResultPrs::Sel_Result;
378   }
379   QString aType = theType.toLower();
380   if(myShapeTypes.contains(aType))
381     return myShapeTypes[aType];
382   Events_InfoMessage("ModuleBase_Tools", "Shape type defined in XML is not implemented!").send();
383   return TopAbs_SHAPE;
384 }
385
386 void checkObjects(const QObjectPtrList& theObjects, bool& hasResult, bool& hasFeature,
387                   bool& hasParameter, bool& hasCompositeOwner, bool& hasResultInHistory,
388                   bool& hasFolder)
389 {
390   hasResult = false;
391   hasFeature = false;
392   hasParameter = false;
393   hasCompositeOwner = false;
394   hasResultInHistory = false;
395   hasFolder = false;
396   foreach(ObjectPtr aObj, theObjects) {
397     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
398     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
399     FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(aObj);
400     ResultParameterPtr aConstruction = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aResult);
401
402     hasResult |= (aResult.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 = 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 (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
997       aPartFeatureNames.append(aFeature->name().c_str());
998     else
999       anOtherFeatureNames.append(aFeature->name().c_str());
1000   }
1001   aPartFeatureNames.sort();
1002   anOtherFeatureNames.sort();
1003
1004   bool aCanReplaceParameters = !aFeaturesRefsToParameterOnly.empty();
1005
1006   QMessageBox aMessageBox(theParent);
1007   aMessageBox.setWindowTitle(QObject::tr("Delete features"));
1008   aMessageBox.setIcon(QMessageBox::Warning);
1009   aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1010   aMessageBox.setDefaultButton(QMessageBox::No);
1011
1012   QString aText;
1013   if (!thePrefixInfo.empty())
1014     aText = thePrefixInfo.c_str();
1015   QString aSep = ", ";
1016   if (!aPartFeatureNames.empty()) {
1017     aText += QString(QObject::tr("The following parts will be deleted: %1.\n"))
1018              .arg(aPartFeatureNames.join(aSep));
1019   }
1020   if (!aNotActivatedDocWrn.isEmpty())
1021     aText += aNotActivatedDocWrn;
1022   if (!anOtherFeatureNames.empty()) {
1023     const char* aMsg = "Features are used in the following features: %1.\nThese "
1024                        "features will be deleted.\n";
1025     aText += QString(QObject::tr(aMsg))
1026                      .arg(anOtherFeatureNames.join(aSep));
1027   }
1028   if (!aParamFeatureNames.empty()) {
1029     const char* aMsg = "Parameters are used directly and through a sequence "
1030                        "of dependencies in the following features: %1.\nThese features will "
1031                        "be deleted.\nOr parameters could be replaced by their values.\n";
1032     aText += QString(QObject::tr(aMsg))
1033                      .arg(aParamFeatureNames.join(aSep));
1034     QPushButton *aReplaceButton =
1035       aMessageBox.addButton(QObject::tr("Replace"), QMessageBox::ActionRole);
1036   }
1037
1038   if (!aText.isEmpty()) {
1039     aText += "Would you like to continue?";
1040     aMessageBox.setText(aText);
1041     aMessageBox.exec();
1042     QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1043
1044     if (aButtonRole == QMessageBox::NoRole)
1045       return false;
1046
1047     if (aButtonRole == QMessageBox::ActionRole) {
1048       foreach (FeaturePtr aObj, aParameterFeatures)
1049         ModelAPI_ReplaceParameterMessage::send(aObj, 0);
1050     }
1051     else
1052       theReferencesToDelete.insert(aFeaturesRefsToParameterOnly.begin(),
1053                                    aFeaturesRefsToParameterOnly.end());
1054   }
1055   return true;
1056 }
1057
1058 //**************************************************************
1059 void convertToFeatures(const QObjectPtrList& theObjects, std::set<FeaturePtr>& theFeatures)
1060 {
1061   QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1062   for(; anIt != aLast; anIt++) {
1063     ObjectPtr anObject = *anIt;
1064     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1065     // for parameter result, use the corresponded reature to be removed
1066     if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1067       aFeature = ModelAPI_Feature::feature(anObject);
1068     }
1069     if (aFeature.get())
1070       theFeatures.insert(aFeature);
1071   }
1072 }
1073
1074 //**************************************************************
1075 void convertToFolders(const QObjectPtrList& theObjects,
1076                                          std::set<FolderPtr>& theFolders)
1077 {
1078   QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1079   for(; anIt != aLast; anIt++) {
1080     ObjectPtr anObject = *anIt;
1081     FolderPtr aFeature = std::dynamic_pointer_cast<ModelAPI_Folder>(anObject);
1082     if (aFeature.get())
1083       theFolders.insert(aFeature);
1084   }
1085 }
1086
1087
1088 //**************************************************************
1089 QString translate(const Events_InfoMessage& theMessage)
1090 {
1091   QString aMessage;
1092
1093   if (!theMessage.empty()) {
1094     std::string aStr = Config_Translator::translate(theMessage);
1095     if (!aStr.empty()) {
1096       std::string aCodec = Config_Translator::codec(theMessage);
1097       aMessage = QTextCodec::codecForName(aCodec.c_str())->toUnicode(aStr.c_str());
1098     }
1099   }
1100
1101   return aMessage;
1102 }
1103
1104 QString translate(const std::string& theContext, const std::string& theMessage)
1105 {
1106   QString aMessage;
1107
1108   if (!theMessage.empty()) {
1109     std::string aStr = Config_Translator::translate(theContext, theMessage);
1110     if (!aStr.empty()) {
1111       std::string aCodec = Config_Translator::codec(theContext);
1112       aMessage = QTextCodec::codecForName(aCodec.c_str())->toUnicode(aStr.c_str());
1113     }
1114   }
1115
1116   return aMessage;
1117 }
1118
1119 void setPointBallHighlighting(AIS_Shape* theAIS)
1120 {
1121   static Handle(Image_AlienPixMap) aPixMap;
1122   if(aPixMap.IsNull()) {
1123     // Load icon for the presentation
1124     std::string aFile;
1125     char* anEnv = getenv("SHAPER_ROOT_DIR");
1126     if(anEnv) {
1127       aFile = std::string(anEnv) +
1128         FSEP + "share" + FSEP + "salome" + FSEP + "resources" + FSEP + "shaper";
1129     } else {
1130       anEnv = getenv("OPENPARTS_ROOT_DIR");
1131       if (anEnv)
1132         aFile = std::string(anEnv) + FSEP + "resources";
1133     }
1134
1135     aFile += FSEP;
1136     static const std::string aMarkerName = "marker_dot.png";
1137     aFile += aMarkerName;
1138     aPixMap = new Image_AlienPixMap();
1139     if(!aPixMap->Load(aFile.c_str())) {
1140       // The icon for constraint is not found
1141       static const std::string aMsg =
1142         "Error: Point market not found by path: \"" + aFile + "\". Falling back.";
1143       //Events_InfoMessage("ModuleBase_Tools::setPointBallHighlighting", aMsg).send();
1144     }
1145   }
1146
1147   Handle(Graphic3d_AspectMarker3d) anAspect;
1148   Handle(Prs3d_Drawer) aDrawer = theAIS->DynamicHilightAttributes();
1149   if (aDrawer.IsNull()) {
1150     if (ModuleBase_IViewer::DefaultHighlightDrawer.IsNull())
1151       return;
1152     aDrawer = new Prs3d_Drawer(*ModuleBase_IViewer::DefaultHighlightDrawer);
1153     if (!aDrawer->HasOwnPointAspect()) {
1154       aDrawer->SetPointAspect(new Prs3d_PointAspect(Aspect_TOM_BALL, Quantity_NOC_BLACK, 2.0));
1155     }
1156   }
1157   if(aDrawer->HasOwnPointAspect()) {
1158     Handle(Prs3d_PointAspect) aPntAspect = aDrawer->PointAspect();
1159     if(aPixMap->IsEmpty()) {
1160       anAspect = aPntAspect->Aspect();
1161       anAspect->SetType(Aspect_TOM_BALL);
1162     } else {
1163       if(aPixMap->Format() == Image_PixMap::ImgGray) {
1164         aPixMap->SetFormat (Image_PixMap::ImgAlpha);
1165       } else if(aPixMap->Format() == Image_PixMap::ImgGrayF) {
1166         aPixMap->SetFormat (Image_PixMap::ImgAlphaF);
1167       }
1168       anAspect = new Graphic3d_AspectMarker3d(aPixMap);
1169       aPntAspect->SetAspect(anAspect);
1170     }
1171     aDrawer->SetPointAspect(aPntAspect);
1172           theAIS->SetDynamicHilightAttributes(aDrawer);
1173   }
1174 }
1175
1176 FeaturePtr createParameter(const QString& theText)
1177 {
1178   FeaturePtr aParameter;
1179   QStringList aList = theText.split("=");
1180   if (aList.count() != 2) {
1181     return aParameter;
1182   }
1183   QString aParamName = aList.at(0).trimmed();
1184
1185   if (isNameExist(aParamName, FeaturePtr())) {
1186     return aParameter;
1187   }
1188
1189   if (!ModelAPI_Expression::isVariable(aParamName.toStdString())) {
1190     return aParameter;
1191   }
1192
1193   QString aExpression = aList.at(1).trimmed();
1194   if (aExpression.isEmpty()) {
1195     return aParameter;
1196   }
1197
1198   SessionPtr aMgr = ModelAPI_Session::get();
1199   std::shared_ptr<ModelAPI_Document> aDoc = aMgr->activeDocument();
1200
1201   aParameter = aDoc->addFeature("Parameter");
1202   if (aParameter.get()) {
1203     AttributeStringPtr aNameAttr = aParameter->string("variable");
1204     aNameAttr->setValue(aParamName.toStdString());
1205
1206     AttributeStringPtr aExprAttr = aParameter->string("expression");
1207     aExprAttr->setValue(aExpression.toStdString());
1208     aParameter->execute();
1209
1210     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1211     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
1212   }
1213   return aParameter;
1214 }
1215
1216 void editParameter(FeaturePtr theParam, const QString& theText)
1217 {
1218   QStringList aList = theText.split("=");
1219   QString aParamName = aList.at(0).trimmed();
1220
1221   QString aExpression = aList.at(1).trimmed();
1222   if (aExpression.isEmpty()) {
1223     return;
1224   }
1225
1226   if (isNameExist(aParamName, theParam)) {
1227     return;
1228   }
1229   AttributeStringPtr aNameAttr = theParam->string("variable");
1230   aNameAttr->setValue(aParamName.toStdString());
1231
1232   AttributeStringPtr aExprAttr = theParam->string("expression");
1233   aExprAttr->setValue(aExpression.toStdString());
1234   theParam->execute();
1235
1236   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
1237 }
1238
1239 bool isNameExist(const QString& theName, FeaturePtr theIgnoreParameter)
1240 {
1241   SessionPtr aMgr = ModelAPI_Session::get();
1242   std::shared_ptr<ModelAPI_Document> aDoc = aMgr->activeDocument();
1243   FeaturePtr aParamFeature;
1244   int aNbFeatures = aDoc->numInternalFeatures();
1245   std::string aName = theName.toStdString();
1246   for (int i = 0; i < aNbFeatures; i++) {
1247     aParamFeature = aDoc->internalFeature(i);
1248     if (aParamFeature && aParamFeature->getKind() == "Parameter") {
1249       if ((theIgnoreParameter != aParamFeature) && (aParamFeature->name() == aName))
1250         return true;
1251     }
1252   }
1253   return false;
1254 }
1255
1256 FeaturePtr findParameter(const QString& theName)
1257 {
1258   SessionPtr aMgr = ModelAPI_Session::get();
1259   std::shared_ptr<ModelAPI_Document> aDoc = aMgr->activeDocument();
1260   FeaturePtr aParamFeature;
1261   int aNbFeatures = aDoc->numInternalFeatures();
1262   std::string aName = theName.toStdString();
1263   for (int i = 0; i < aNbFeatures; i++) {
1264     aParamFeature = aDoc->internalFeature(i);
1265     if (aParamFeature && aParamFeature->getKind() == "Parameter") {
1266       if (aParamFeature->name() == aName)
1267         return aParamFeature;
1268     }
1269   }
1270   return FeaturePtr();
1271 }
1272
1273
1274 //********************************************************************
1275 std::string generateName(const AttributePtr& theAttribute,
1276   ModuleBase_IWorkshop* theWorkshop)
1277 {
1278   std::string aName;
1279   if (theAttribute.get() != NULL) {
1280     ModuleBase_Operation* anOperation = theWorkshop->currentOperation();
1281
1282     FeaturePtr aFeature = ModelAPI_Feature::feature(theAttribute->owner());
1283     if (aFeature.get()) {
1284       std::string aXmlCfg, aDescription;
1285       theWorkshop->module()->getXMLRepresentation(aFeature->getKind(), aXmlCfg, aDescription);
1286
1287       ModuleBase_WidgetFactory aFactory(aXmlCfg, theWorkshop);
1288       std::string anAttributeTitle;
1289       aFactory.getAttributeTitle(theAttribute->id(), anAttributeTitle);
1290
1291       std::stringstream aStreamName;
1292       aStreamName << theAttribute->owner()->data()->name() << "/" << anAttributeTitle.c_str();
1293       aName = aStreamName.str();
1294     }
1295   }
1296   return aName;
1297 }
1298
1299 } // namespace ModuleBase_Tools
1300
1301