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