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