]> SALOME platform Git repositories - modules/shaper.git/blob - src/PartSet/PartSet_Module.cpp
Salome HOME
4fc3b6ab0c559bea32490b2f63efac028656fe6d
[modules/shaper.git] / src / PartSet / PartSet_Module.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 #include "PartSet_Module.h"
4 #include "PartSet_WidgetSketchLabel.h"
5 #include "PartSet_Validators.h"
6 #include "PartSet_Tools.h"
7 #include "PartSet_PreviewPlanes.h"
8 #include "PartSet_WidgetPoint2d.h"
9 #include "PartSet_WidgetPoint2dDistance.h"
10 #include "PartSet_WidgetPoint2DFlyout.h"
11 #include "PartSet_WidgetShapeSelector.h"
12 #include "PartSet_WidgetMultiSelector.h"
13 #include "PartSet_WidgetSubShapeSelector.h"
14 #include "PartSet_WidgetEditor.h"
15 #include "PartSet_WidgetFileSelector.h"
16 #include "PartSet_WidgetSketchCreator.h"
17 #include "PartSet_SketcherMgr.h"
18 #include "PartSet_SketcherReetntrantMgr.h"
19 #include "PartSet_ResultSketchPrs.h"
20 #include "PartSet_MenuMgr.h"
21 #include "PartSet_CustomPrs.h"
22 #include "PartSet_IconFactory.h"
23 #include "PartSet_WidgetChoice.h"
24 #include "PartSet_OverconstraintListener.h"
25
26 #include "PartSet_Filters.h"
27 #include "PartSet_FilterInfinite.h"
28
29 #include <PartSetPlugin_Remove.h>
30 #include <PartSetPlugin_Part.h>
31 #include <PartSetPlugin_Duplicate.h>
32
33 #include <ModuleBase_Operation.h>
34 #include <ModuleBase_OperationAction.h>
35 #include <ModuleBase_IViewer.h>
36 #include <ModuleBase_IViewWindow.h>
37 #include <ModuleBase_IPropertyPanel.h>
38 #include <ModuleBase_WidgetEditor.h>
39 #include <ModuleBase_WidgetValidated.h>
40 #include <ModuleBase_Tools.h>
41 #include <ModuleBase_OperationFeature.h>
42 #include <ModuleBase_WidgetFactory.h>
43 #include <ModuleBase_OperationDescription.h>
44 #include <ModuleBase_ViewerPrs.h>
45
46 #include <ModelAPI_Object.h>
47 #include <ModelAPI_Events.h>
48 #include <ModelAPI_Validator.h>
49 #include <ModelAPI_Data.h>
50 #include <ModelAPI_Session.h>
51 #include <ModelAPI_ResultBody.h>
52 #include <ModelAPI_AttributeString.h>
53 #include <ModelAPI_AttributeSelectionList.h>
54 #include <ModelAPI_Tools.h>
55 #include <ModelAPI_ResultConstruction.h>
56
57 #include <GeomDataAPI_Point2D.h>
58 #include <GeomDataAPI_Point.h>
59 #include <GeomDataAPI_Dir.h>
60
61 #include <XGUI_Displayer.h>
62 #include <XGUI_Workshop.h>
63 #include <XGUI_OperationMgr.h>
64 #include <XGUI_PropertyPanel.h>
65 #include <XGUI_ModuleConnector.h>
66 #include <XGUI_ContextMenuMgr.h>
67 #include <XGUI_Tools.h>
68 #include <XGUI_ObjectsBrowser.h>
69 #include <XGUI_SelectionMgr.h>
70 #include <XGUI_DataModel.h>
71 #include <XGUI_ErrorMgr.h>
72 #include <XGUI_CustomPrs.h>
73 #include <XGUI_SelectionMgr.h>
74 #include <XGUI_ActionsMgr.h>
75
76 #include <SketchPlugin_Feature.h>
77 #include <SketchPlugin_Sketch.h>
78 #include <SketchPlugin_ConstraintAngle.h>
79 #include <SketchPlugin_ConstraintLength.h>
80 #include <SketchPlugin_ConstraintDistance.h>
81 #include <SketchPlugin_ConstraintParallel.h>
82 #include <SketchPlugin_ConstraintPerpendicular.h>
83 #include <SketchPlugin_ConstraintRadius.h>
84
85 #include <SketcherPrs_SymbolPrs.h>
86 #include <SketcherPrs_Coincident.h>
87 #include <SketcherPrs_Tools.h>
88
89 #include <Events_Loop.h>
90 #include <Config_PropManager.h>
91 #include <Config_Keywords.h>
92
93 #include <AIS_Dimension.hxx>
94 #include <AIS_InteractiveObject.hxx>
95 #include <StdSelect_TypeOfFace.hxx>
96 #include <TopoDS_Vertex.hxx>
97 #include <TopoDS.hxx>
98 #include <TopoDS_Shape.hxx>
99 #include <BRep_Tool.hxx>
100
101 #include <QObject>
102 #include <QMouseEvent>
103 #include <QString>
104 #include <QTimer>
105 #include <QApplication>
106 #include <QMessageBox>
107 #include <QMainWindow>
108 #include <QLineEdit>
109 #include <QString>
110
111 #include <GeomAlgoAPI_FaceBuilder.h>
112 #include <GeomDataAPI_Dir.h>
113
114 #include <SelectMgr_ListIteratorOfListOfFilter.hxx>
115
116 #ifdef _DEBUG
117 #include <QDebug>
118 #endif
119
120 /*!Create and return new instance of XGUI_Module*/
121 extern "C" PARTSET_EXPORT ModuleBase_IModule* createModule(ModuleBase_IWorkshop* theWshop)
122 {
123   return new PartSet_Module(theWshop);
124 }
125
126 PartSet_Module::PartSet_Module(ModuleBase_IWorkshop* theWshop)
127 : ModuleBase_IModule(theWshop),
128   myVisualLayerId(0),
129   myIsOperationIsLaunched(false)
130 {
131   new PartSet_IconFactory();
132
133   mySketchMgr = new PartSet_SketcherMgr(this);
134   mySketchReentrantMgr = new PartSet_SketcherReetntrantMgr(theWshop);
135
136   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWshop);
137   XGUI_Workshop* aWorkshop = aConnector->workshop();
138
139   ModuleBase_IViewer* aViewer = theWshop->viewer();
140   connect(aViewer, SIGNAL(keyRelease(ModuleBase_IViewWindow*, QKeyEvent*)),
141           this, SLOT(onKeyRelease(ModuleBase_IViewWindow*, QKeyEvent*)));
142   connect(aViewer, SIGNAL(viewTransformed(int)),
143           SLOT(onViewTransformed(int)));
144   connect(aViewer, SIGNAL(viewCreated(ModuleBase_IViewWindow*)),
145           SLOT(onViewCreated(ModuleBase_IViewWindow*)));
146   myMenuMgr = new PartSet_MenuMgr(this);
147   myCustomPrs = new PartSet_CustomPrs(theWshop);
148
149   myOverconstraintListener = new PartSet_OverconstraintListener(theWshop);
150
151   Events_Loop* aLoop = Events_Loop::loop();
152   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_DOCUMENT_CHANGED));
153
154   mySelectionFilters.Append(new PartSet_GlobalFilter(myWorkshop));
155   mySelectionFilters.Append(new PartSet_FilterInfinite(myWorkshop));
156
157   setDefaultConstraintShown();
158
159   Config_PropManager::registerProp("Visualization", "operation_parameter_color",
160                           "Reference shape wireframe color in operation", Config_Prop::Color,
161                           PartSet_CustomPrs::OPERATION_PARAMETER_COLOR());
162   Config_PropManager::registerProp("Visualization", "operation_result_color",
163                           "Result shape wireframe color in operation", Config_Prop::Color,
164                           PartSet_CustomPrs::OPERATION_RESULT_COLOR());
165   Config_PropManager::registerProp("Visualization", "operation_highlight_color",
166                           "Multi selector item color in operation", Config_Prop::Color,
167                           PartSet_CustomPrs::OPERATION_HIGHLIGHT_COLOR());
168 }
169
170 PartSet_Module::~PartSet_Module()
171 {
172   SelectMgr_ListIteratorOfListOfFilter aIt(mySelectionFilters);
173   for (; aIt.More(); aIt.Next()) {
174     Handle(SelectMgr_Filter) aFilter = aIt.Value();
175     if (!aFilter.IsNull())
176       aFilter.Nullify();
177   }
178   delete myCustomPrs;
179   delete myOverconstraintListener;
180 }
181
182 void PartSet_Module::activateSelectionFilters()
183 {
184   SelectMgr_ListIteratorOfListOfFilter aIt(mySelectionFilters);
185   for (; aIt.More(); aIt.Next()) {
186     Handle(SelectMgr_Filter) aFilter = aIt.Value();
187     if (!aFilter.IsNull())
188       myWorkshop->viewer()->addSelectionFilter(aFilter);
189   }
190 }
191
192 void PartSet_Module::deactivateSelectionFilters()
193 {
194   SelectMgr_ListIteratorOfListOfFilter aIt(mySelectionFilters);
195   for (; aIt.More(); aIt.Next()) {
196     Handle(SelectMgr_Filter) aFilter = aIt.Value();
197     if (!aFilter.IsNull())
198       myWorkshop->viewer()->removeSelectionFilter(aFilter);
199   }
200 }
201
202 void PartSet_Module::storeSelection()
203 {
204   sketchMgr()->storeSelection();
205 }
206
207 void PartSet_Module::restoreSelection()
208 {
209   sketchMgr()->restoreSelection();
210 }
211
212 void PartSet_Module::registerValidators()
213 {
214   //Registering of validators
215   SessionPtr aMgr = ModelAPI_Session::get();
216   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
217   aFactory->registerValidator("PartSet_DistanceSelection", new PartSet_DistanceSelection);
218   aFactory->registerValidator("PartSet_LengthSelection", new PartSet_LengthSelection);
219   aFactory->registerValidator("PartSet_PerpendicularSelection", new PartSet_PerpendicularSelection);
220   aFactory->registerValidator("PartSet_ParallelSelection", new PartSet_ParallelSelection);
221   aFactory->registerValidator("PartSet_RadiusSelection", new PartSet_RadiusSelection);
222   aFactory->registerValidator("PartSet_RigidSelection", new PartSet_RigidSelection);
223   aFactory->registerValidator("PartSet_CoincidentSelection", new PartSet_CoincidentSelection);
224   aFactory->registerValidator("PartSet_HVDirSelection", new PartSet_HVDirSelection);
225   aFactory->registerValidator("PartSet_TangentSelection", new PartSet_TangentSelection);
226   aFactory->registerValidator("PartSet_FilletSelection", new PartSet_FilletSelection);
227   aFactory->registerValidator("PartSet_AngleSelection", new PartSet_AngleSelection);
228   aFactory->registerValidator("PartSet_EqualSelection", new PartSet_EqualSelection);
229   aFactory->registerValidator("PartSet_CollinearSelection", new PartSet_CollinearSelection);
230   aFactory->registerValidator("PartSet_MiddlePointSelection", new PartSet_MiddlePointSelection);
231   aFactory->registerValidator("PartSet_DifferentObjects", new PartSet_DifferentObjectsValidator);
232   aFactory->registerValidator("PartSet_CoincidentAttr", new PartSet_CoincidentAttr);
233   aFactory->registerValidator("PartSet_MultyTranslationSelection",
234     new PartSet_MultyTranslationSelection);
235   aFactory->registerValidator("PartSet_SplitSelection", new PartSet_SplitSelection);
236   aFactory->registerValidator("PartSet_ProjectionSelection", new PartSet_ProjectionSelection);
237 }
238
239 void PartSet_Module::registerProperties()
240 {
241   Config_PropManager::registerProp(SKETCH_TAB_NAME, "planes_size", "Size", Config_Prop::Double,
242                                    PLANE_SIZE);
243   Config_PropManager::registerProp(SKETCH_TAB_NAME, "planes_thickness", "Thickness",
244                                    Config_Prop::Integer, SKETCH_WIDTH);
245   Config_PropManager::registerProp(SKETCH_TAB_NAME, "rotate_to_plane",
246     "Rotate to plane when selected", Config_Prop::Boolean, "false");
247 }
248
249 void PartSet_Module::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget,
250                                             const bool isToConnect)
251 {
252   mySketchMgr->connectToPropertyPanel(theWidget, isToConnect);
253 }
254
255 void PartSet_Module::operationCommitted(ModuleBase_Operation* theOperation)
256 {
257   if (sketchMgr()->isNestedSketchOperation(theOperation)) {
258     mySketchMgr->commitNestedSketch(theOperation);
259   }
260
261   /// Restart sketcher operations automatically
262   if (!mySketchReentrantMgr->operationCommitted(theOperation)) {
263
264     ModuleBase_OperationFeature* aFOperation =
265       dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
266     if (aFOperation && !aFOperation->isEditOperation()) {
267       // the selection is cleared after commit the create operation
268       // in order to do not use the same selected objects in the restarted operation
269       // for common behaviour, the selection is cleared even if the operation is not restarted
270       getWorkshop()->selector()->clearSelection();
271     }
272   }
273 }
274
275 void PartSet_Module::operationAborted(ModuleBase_Operation* theOperation)
276 {
277   /// Restart sketcher operations automatically
278   mySketchReentrantMgr->operationAborted(theOperation);
279 }
280
281 void PartSet_Module::operationStarted(ModuleBase_Operation* theOperation)
282 {
283   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
284                                                                                 (theOperation);
285   if (aFOperation) {
286     XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(workshop());
287     XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
288
289     ModuleBase_ModelWidget* aFilledWidget = 0;
290     bool aPostonedWidgetActivation = false;
291
292     FeaturePtr aFeature = aFOperation->feature();
293     /// Restart sketcher operations automatically
294     /// it is important to call method of sketch reentrant manager before filling of PP
295     /// because it fills some created feature attributes, these new values should be used
296     /// to fill the property panel
297     mySketchReentrantMgr->operationStarted(theOperation);
298
299     aWorkshop->fillPropertyPanel(aFOperation);
300     // filling the operation values by the current selection
301     // if the operation can be committed after the controls filling, the method perform should
302     // be stopped. Otherwise unnecessary presentations can be shown(e.g. operation prs in sketch)
303     bool isOperationCommitted = false;
304     if (!aFOperation->isEditOperation()) {
305       std::string aGreedAttributeId = ModuleBase_Tools::findGreedAttribute(workshop(), aFeature);
306       // if there is a greed attribute, automatic commit by preselection
307       // for this feature is prohibited
308       aFilledWidget = aFOperation->activateByPreselection(aGreedAttributeId);
309       if (currentOperation() != aFOperation)
310         isOperationCommitted = true;
311       else {
312         if (aGreedAttributeId.empty()) {
313           // a signal should be emitted before the next widget activation
314           // because, the activation of the next widget will give a focus to the widget.
315           // As a result the value of the widget is initialized.
316           // And commit may happens until the value is entered.
317           if (aFilledWidget) {
318             if (mySketchReentrantMgr->canBeCommittedByPreselection())
319               isOperationCommitted = mySketchMgr->operationActivatedByPreselection();
320             // activate the next obligatory widget
321             if (!isOperationCommitted)
322               aPropertyPanel->activateNextWidget(aFilledWidget);
323           }
324         }
325         else { // there is a greed widget
326           const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
327           std::string aFirstAttributeId = aWidgets.front()->attributeID();
328           // activate next widget after greeded if it is the first widget in the panel
329           // else the first panel widget is already activated by operation start
330           if (aFirstAttributeId == aGreedAttributeId)
331             aPostonedWidgetActivation = true;
332         }
333       }
334     } if (!isOperationCommitted) {
335       aWorkshop->connectToPropertyPanel(true);
336       updateSketcherOnStart(aFOperation);
337       updatePresentationsOnStart(aFOperation);
338
339       // the objects of the current operation should be deactivated
340       QObjectPtrList anObjects;
341       anObjects.append(aFeature);
342       std::list<ResultPtr> aResults;
343       ModelAPI_Tools::allResults(aFeature, aResults);
344       std::list<ResultPtr>::const_iterator aIt;
345       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
346         anObjects.append(*aIt);
347       }
348       QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
349       for (; anIt != aLast; anIt++)
350         aWorkshop->deactivateActiveObject(*anIt, false);
351       if (anObjects.size() > 0) {
352         XGUI_Displayer* aDisplayer = aWorkshop->displayer();
353         aDisplayer->updateViewer();
354       }
355       /// state of command actions should be updated after displayed objects modification because
356       /// deactivation(for example) of objects may influence on selection in the viewer
357       /// State of command actions may depend on selection in the viewer(e.g. Sketch)
358       workshop()->updateCommandStatus();
359     }
360     if (aPostonedWidgetActivation) {
361       // if the widget is an empty in the chain of activated widgets, the current operation
362       // is restarted. It should be performed after functionality of the operation starting
363       aPropertyPanel->activateNextWidget(aFilledWidget);
364     }
365   }
366 }
367
368 void PartSet_Module::updateSketcherOnStart(ModuleBase_Operation* theOperation)
369 {
370   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
371     mySketchMgr->startSketch(theOperation);
372   }
373   else if (sketchMgr()->isNestedSketchOperation(theOperation)) {
374     mySketchMgr->startNestedSketch(theOperation);
375   }
376 }
377
378 void PartSet_Module::updatePresentationsOnStart(ModuleBase_Operation* theOperation)
379 {
380   ModuleBase_OperationFeature* aFOperation =
381     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
382   if (aFOperation) {
383     myCustomPrs->activate(aFOperation->feature(), ModuleBase_IModule::CustomizeArguments, true);
384     myCustomPrs->activate(aFOperation->feature(), ModuleBase_IModule::CustomizeResults, true);
385   }
386 }
387
388 void PartSet_Module::operationResumed(ModuleBase_Operation* theOperation)
389 {
390   ModuleBase_IModule::operationResumed(theOperation);
391
392   ModuleBase_OperationFeature* aFOperation =
393     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
394   if (aFOperation) {
395     myCustomPrs->activate(aFOperation->feature(), ModuleBase_IModule::CustomizeArguments, true);
396     myCustomPrs->activate(aFOperation->feature(), ModuleBase_IModule::CustomizeResults, true);
397   }
398 }
399
400 void PartSet_Module::operationStopped(ModuleBase_Operation* theOperation)
401 {
402   bool isModifiedArgs = myCustomPrs->deactivate(ModuleBase_IModule::CustomizeArguments, false);
403   bool isModifiedResults = myCustomPrs->deactivate(ModuleBase_IModule::CustomizeResults, false);
404   bool isModified = isModifiedArgs || isModifiedResults;
405
406   if (sketchMgr()->isNestedSketchOperation(theOperation)) {
407     mySketchMgr->stopNestedSketch(theOperation);
408   }
409   else if (PartSet_SketcherMgr::isSketchOperation(theOperation))
410     setDefaultConstraintShown();
411
412   //VSV: Viewer is updated on feature update and redisplay
413   if (isModified) {
414     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myWorkshop);
415     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
416     aDisplayer->updateViewer();
417   }
418
419   QMap<PartSet_Tools::ConstraintVisibleState, bool>::const_iterator
420     anIt = myHasConstraintShown.begin(), aLast = myHasConstraintShown.end();
421   for (; anIt != aLast; anIt++) {
422     mySketchMgr->updateBySketchParameters(anIt.key(), anIt.value());
423   }
424 }
425
426 ModuleBase_Operation* PartSet_Module::currentOperation() const
427 {
428   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
429   XGUI_OperationMgr* anOpMgr = aConnector->workshop()->operationMgr();
430   return anOpMgr->currentOperation();
431 }
432
433 bool PartSet_Module::canUndo() const
434 {
435   bool aCanUndo = false;
436   SessionPtr aMgr = ModelAPI_Session::get();
437   if (aMgr->hasModuleDocument() && aMgr->canUndo()) {
438     aCanUndo = !aMgr->isOperation();
439     if (!aCanUndo) // check the enable state additionally by sketch manager
440       aCanUndo = aMgr->canUndo();
441   }
442   return aCanUndo;
443 }
444
445 bool PartSet_Module::canRedo() const
446 {
447   bool aCanRedo = false;
448   SessionPtr aMgr = ModelAPI_Session::get();
449   if (aMgr->hasModuleDocument() && aMgr->canRedo()) {
450     aCanRedo = !aMgr->isOperation();
451     if (!aCanRedo) // check the enable state additionally by sketch manager
452       aCanRedo = aMgr->canRedo();
453   }
454   return aCanRedo;
455 }
456
457 bool PartSet_Module::canApplyAction(const ObjectPtr& theObject, const QString& theActionId) const
458 {
459   bool aValid = true;
460   if (theActionId == "MOVE_CMD") {
461     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
462     if (aFeature) {
463       ResultPtr aResult = ModuleBase_Tools::firstResult(aFeature);
464       // part features can not be moved in the history.
465       if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group())
466         aValid = false;
467     }
468   }
469   return aValid;
470 }
471
472 bool PartSet_Module::canEraseObject(const ObjectPtr& theObject) const
473 {
474   // the sketch manager put the restriction to the objects erase
475   return mySketchMgr->canEraseObject(theObject);
476 }
477
478 bool PartSet_Module::canDisplayObject(const ObjectPtr& theObject) const
479 {
480   // the sketch manager put the restriction to the objects display
481   return mySketchMgr->canDisplayObject(theObject);
482 }
483
484 /*void PartSet_Module::processHiddenObject(const std::list<ObjectPtr>& theObjects)
485 {
486   mySketchMgr->processHiddenObject(theObjects);
487 }*/
488
489 bool PartSet_Module::canActivateSelection(const ObjectPtr& theObject) const
490 {
491   bool aCanActivate = ModuleBase_IModule::canActivateSelection(theObject);
492
493   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
494   bool isSketchOp = PartSet_SketcherMgr::isSketchOperation(anOperation),
495        isNestedOp = sketchMgr()->isNestedSketchOperation(anOperation);
496   if (isSketchOp || isNestedOp) {
497     // in active sketch operation it is possible to activate operation object in selection
498     // in the edit operation, e.g. points of the line can be moved when the line is edited
499     ModuleBase_OperationFeature* aFOperation =
500       dynamic_cast<ModuleBase_OperationFeature*>(anOperation);
501     aCanActivate = aCanActivate || (aFOperation && aFOperation->isEditOperation());
502   }
503   return aCanActivate;
504 }
505
506 bool PartSet_Module::addViewerMenu(const QMap<QString, QAction*>& theStdActions,
507                                    QWidget* theParent,
508                                    QMap<int, QAction*>& theMenuActions) const
509 {
510   return myMenuMgr->addViewerMenu(theStdActions, theParent, theMenuActions);
511 }
512
513 void PartSet_Module::updateViewerMenu(const QMap<QString, QAction*>& theStdActions)
514 {
515   myMenuMgr->updateViewerMenu(theStdActions);
516 }
517
518 bool PartSet_Module::isActionEnableStateFixed(const int theActionId) const
519 {
520   bool isEnabledFixed = false;
521   if (theActionId == XGUI_ActionsMgr::AcceptAll &&
522       mySketchReentrantMgr->isInternalEditStarted())
523     isEnabledFixed = true;
524   return isEnabledFixed;
525 }
526
527 QString PartSet_Module::getFeatureError(const FeaturePtr& theFeature)
528 {
529   QString anError = ModuleBase_IModule::getFeatureError(theFeature);
530   if (anError.isEmpty())
531     anError = sketchMgr()->getFeatureError(theFeature);
532
533   return anError;
534 }
535
536 void PartSet_Module::grantedOperationIds(ModuleBase_Operation* theOperation,
537                                          QStringList& theIds) const
538 {
539   myMenuMgr->grantedOperationIds(theOperation, theIds);
540
541   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
542     XGUI_Workshop* aWorkshop = getWorkshop();
543     theIds.append(aWorkshop->contextMenuMgr()->action("DELETE_CMD")->text());
544   }
545 }
546
547 void PartSet_Module::activeSelectionModes(QIntList& theModes)
548 {
549   theModes.clear();
550   if (mySketchMgr->activeSketch().get())
551     PartSet_SketcherMgr::sketchSelectionModes(theModes);
552 }
553
554 void PartSet_Module::customSubShapesSelectionModes(QIntList& theTypes)
555 {
556   if (theTypes.contains(TopAbs_FACE))
557     theTypes.append(SketcherPrs_Tools::Sel_Sketch_Face);
558   if (theTypes.contains(TopAbs_WIRE))
559     theTypes.append(SketcherPrs_Tools::Sel_Sketch_Wire);
560 }
561
562 bool PartSet_Module::isMouseOverWindow()
563 {
564   return mySketchMgr->isMouseOverWindow();
565 }
566
567 bool PartSet_Module::isSketchNeutralPointActivated() const
568 {
569   bool isNeutralPoint = true;
570   if (sketchReentranceMgr()->isInternalEditStarted())
571     isNeutralPoint = false;
572   if (myIsOperationIsLaunched)
573     isNeutralPoint = false;
574
575   return isNeutralPoint;
576 }
577
578 void PartSet_Module::closeDocument()
579 {
580   myActivePartIndex = QModelIndex();
581   clearViewer();
582 }
583
584 void PartSet_Module::clearViewer()
585 {
586   myCustomPrs->clearPrs();
587
588   XGUI_Workshop* aWorkshop = getWorkshop();
589   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
590   aDisplayer->deactivateSelectionFilters();
591 }
592
593 void PartSet_Module::propertyPanelDefined(ModuleBase_Operation* theOperation)
594 {
595   ModuleBase_OperationFeature* aFOperation =
596     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
597   if (!aFOperation)
598     return;
599
600   ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
601   // we have to manually activate the sketch label in edit mode
602   if (PartSet_SketcherMgr::isSketchOperation(aFOperation) &&  (aFOperation->isEditOperation()))
603     aPanel->activateWidget(aPanel->modelWidgets().first());
604 }
605
606 bool PartSet_Module::createWidgets(ModuleBase_Operation* theOperation,
607                                    QList<ModuleBase_ModelWidget*>& theWidgets) const
608 {
609   bool aProcessed = false;
610
611   ModuleBase_OperationFeature* aFOperation =
612     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
613   XGUI_Workshop* aWorkshop = getWorkshop();
614   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
615   if (mySketchMgr->activeSketch().get() && aFOperation && aPropertyPanel) {
616     ModuleBase_ISelection* aSelection = workshop()->selection();
617     // click on a point in sketch leads here with the point is highlighted, not yet selected
618     QList<ModuleBase_ViewerPrsPtr> aPreselection = aSelection->getHighlighted();
619     if (aPreselection.size() == 1) {
620       ModuleBase_ViewerPrsPtr aSelectedPrs = aPreselection[0];
621       ObjectPtr anObject = aSelectedPrs->object();
622
623       FeaturePtr aFeature = ModelAPI_Feature::feature(anObject);
624       FeaturePtr anOpFeature = aFOperation->feature();
625       GeomShapePtr aShape = aSelectedPrs->shape();
626       // click on the digit of dimension constrain comes here
627       // with an empty shape, so we need the check
628       if (aFeature == anOpFeature && aShape.get() && !aShape->isNull()) {
629         // if feature has only one result and shape of result is equal to selected shape
630         // this attribute is not processed. It is a case of Sketch Point.
631         if (aFeature->results().size() == 1) {
632           ResultPtr aResult = aFeature->results().front();
633           if (aResult.get() && aResult->shape()->isEqual(aShape))
634             return aProcessed;
635         }
636         const TopoDS_Shape& aTDShape = aShape->impl<TopoDS_Shape>();
637         AttributePtr anAttribute = PartSet_Tools::findAttributeBy2dPoint(anObject, aTDShape,
638                                                                mySketchMgr->activeSketch());
639         if (anAttribute.get()) {
640           QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
641           ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), workshop());
642
643           const std::string anAttributeId = anAttribute->id();
644           aFactory.createWidget(aPropertyPanel->contentWidget(), anAttributeId);
645
646           theWidgets = aFactory.getModelWidgets();
647           // it is possible that the point does not present in XML definition,
648           // in this case, we assume that it is not processed by this module
649           // e.g. "Intersection point" feature
650           aProcessed = !theWidgets.isEmpty();
651         }
652       }
653     }
654   }
655   return aProcessed;
656 }
657
658 void PartSet_Module::onSelectionChanged()
659 {
660   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
661   if (!aOperation)
662     return;
663
664   bool isSketcherOp = false;
665   // An edit operation is enable only if the current opeation is the sketch operation
666   if (mySketchMgr->activeSketch()) {
667     if (PartSet_Tools::sketchPlane(mySketchMgr->activeSketch()))
668       isSketcherOp = PartSet_SketcherMgr::isSketchOperation(aOperation);
669   }
670   if (isSketcherOp) {
671     // Editing of constraints can be done on selection
672     ModuleBase_ISelection* aSelect = myWorkshop->selection();
673     QList<ModuleBase_ViewerPrsPtr> aSelected = aSelect->getSelected();
674     if (aSelected.size() == 1) {
675       ModuleBase_ViewerPrsPtr aPrs = aSelected.first();
676       ObjectPtr aObject = aPrs->object();
677       FeaturePtr aFeature = ModelAPI_Feature::feature(aObject);
678       if (aFeature) {
679         std::string aId = aFeature->getKind();
680         if ((aId == SketchPlugin_ConstraintRadius::ID()) ||
681             (aId == SketchPlugin_ConstraintLength::ID()) ||
682             (aId == SketchPlugin_ConstraintDistance::ID()) ||
683             (aId == SketchPlugin_ConstraintAngle::ID())) {
684           editFeature(aFeature);
685         }
686       }
687     }
688   }
689 }
690
691 void PartSet_Module::onKeyRelease(ModuleBase_IViewWindow* theWnd, QKeyEvent* theEvent)
692 {
693   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
694   XGUI_OperationMgr* anOpMgr = aConnector->workshop()->operationMgr();
695   anOpMgr->onKeyReleased(theWnd->viewPort(), theEvent);
696 }
697
698 ModuleBase_ModelWidget* PartSet_Module::createWidgetByType(const std::string& theType,
699                                                            QWidget* theParent,
700                                                            Config_WidgetAPI* theWidgetApi)
701 {
702   ModuleBase_IWorkshop* aWorkshop = workshop();
703   XGUI_Workshop* aXUIWorkshop = getWorkshop();
704   ModuleBase_ModelWidget* aWgt = NULL;
705   if (theType == "sketch-start-label") {
706     PartSet_WidgetSketchLabel* aLabelWgt = new PartSet_WidgetSketchLabel(theParent, aWorkshop,
707                                                                theWidgetApi, myHasConstraintShown);
708     connect(aLabelWgt, SIGNAL(planeSelected(const std::shared_ptr<GeomAPI_Pln>&)),
709       mySketchMgr, SLOT(onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>&)));
710     connect(aLabelWgt, SIGNAL(showConstraintToggled(int, bool)),
711       mySketchMgr, SLOT(onShowConstraintsToggle(int, bool)));
712     aWgt = aLabelWgt;
713   } else if (theType == "sketch-2dpoint_selector") {
714     PartSet_WidgetPoint2D* aPointWgt = new PartSet_WidgetPoint2D(theParent, aWorkshop,
715                                                                  theWidgetApi);
716     aPointWgt->setSketch(mySketchMgr->activeSketch());
717     connect(aPointWgt, SIGNAL(vertexSelected()), sketchReentranceMgr(), SLOT(onVertexSelected()));
718     aWgt = aPointWgt;
719   }else if (theType == "sketch-2dpoint_flyout_selector") {
720     PartSet_WidgetPoint2DFlyout* aPointWgt = new PartSet_WidgetPoint2DFlyout(theParent, aWorkshop,
721                                                                              theWidgetApi);
722     aPointWgt->setSketch(mySketchMgr->activeSketch());
723     connect(aPointWgt, SIGNAL(vertexSelected()), sketchReentranceMgr(), SLOT(onVertexSelected()));
724     aWgt = aPointWgt;
725   } else if (theType == "point2ddistance") {
726     PartSet_WidgetPoint2dDistance* aDistanceWgt = new PartSet_WidgetPoint2dDistance(theParent,
727                                                                      aWorkshop, theWidgetApi);
728     aDistanceWgt->setSketch(mySketchMgr->activeSketch());
729     aWgt = aDistanceWgt;
730   } else if (theType == "sketch_shape_selector") {
731     PartSet_WidgetShapeSelector* aShapeSelectorWgt =
732                           new PartSet_WidgetShapeSelector(theParent, aWorkshop, theWidgetApi);
733     aShapeSelectorWgt->setSketcher(mySketchMgr->activeSketch());
734     aWgt = aShapeSelectorWgt;
735   } else if (theType == "sketch_multi_selector") {
736     PartSet_WidgetMultiSelector* aShapeSelectorWgt =
737                           new PartSet_WidgetMultiSelector(theParent, aWorkshop, theWidgetApi);
738     aShapeSelectorWgt->setSketcher(mySketchMgr->activeSketch());
739     aWgt = aShapeSelectorWgt;
740   }
741   else if (theType == "sketch_sub_shape_selector") {
742     PartSet_WidgetSubShapeSelector* aSubShapeSelectorWgt =
743                           new PartSet_WidgetSubShapeSelector(theParent, aWorkshop, theWidgetApi);
744     aSubShapeSelectorWgt->setSketcher(mySketchMgr->activeSketch());
745     aWgt = aSubShapeSelectorWgt;
746   }
747   else if (theType == WDG_DOUBLEVALUE_EDITOR) {
748     aWgt = new PartSet_WidgetEditor(theParent, aWorkshop, theWidgetApi);
749   } else if (theType == "export_file_selector") {
750     aWgt = new PartSet_WidgetFileSelector(theParent, aWorkshop, theWidgetApi);
751   } else if (theType == "sketch_launcher") {
752     aWgt = new PartSet_WidgetSketchCreator(theParent, this, theWidgetApi);
753   } else if (theType == "module_choice") {
754     aWgt = new PartSet_WidgetChoice(theParent, theWidgetApi);
755     connect(aWgt, SIGNAL(itemSelected(ModuleBase_ModelWidget*, int)),
756             this, SLOT(onChoiceChanged(ModuleBase_ModelWidget*, int)));
757   }
758   return aWgt;
759 }
760
761 ModuleBase_ModelWidget* PartSet_Module::activeWidget() const
762 {
763   ModuleBase_ModelWidget* anActiveWidget = 0;
764
765   anActiveWidget = mySketchReentrantMgr->internalActiveWidget();
766   if (!anActiveWidget) {
767     ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
768     if (aOperation) {
769       ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
770       anActiveWidget = aPanel ? aPanel->activeWidget() : 0;
771     }
772   }
773   return anActiveWidget;
774 }
775
776 bool PartSet_Module::deleteObjects()
777 {
778   bool isProcessed = false;
779
780   XGUI_Workshop* aWorkshop = getWorkshop();
781   XGUI_OperationMgr* anOpMgr = aWorkshop->operationMgr();
782
783   //SessionPtr aMgr = ModelAPI_Session::get();
784   // 1. check whether the delete should be processed in the module
785   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
786   bool isSketchOp = PartSet_SketcherMgr::isSketchOperation(anOperation),
787        isNestedOp = sketchMgr()->isNestedSketchOperation(anOperation);
788   if (isSketchOp || isNestedOp) {
789     isProcessed = true;
790     // 2. find selected presentations
791     // selected objects should be collected before the current operation abort because
792     // the abort leads to selection lost on constraint objects. It can be corrected after #386 issue
793     ModuleBase_ISelection* aSel = workshop()->selection();
794     QObjectPtrList aSelectedObj = aSel->selectedPresentations();
795     // if there are no selected objects in the viewer, that means that the selection in another
796     // place cased this method. It is necessary to return the false value to understande in above
797     // method that delete is not processed
798     if (aSelectedObj.count() == 0)
799       return false;
800
801     // avoid delete of the objects, which are not belong to the current sketch
802     // in order to do not delete results of other sketches
803     QObjectPtrList aSketchObjects;
804     QObjectPtrList::const_iterator anIt = aSelectedObj.begin(), aLast = aSelectedObj.end();
805     for ( ; anIt != aLast; anIt++) {
806       ObjectPtr anObject = *anIt;
807       if (mySketchMgr->isObjectOfSketch(anObject)) {
808         // sketch feature should be used in this list because workshop deletes features only
809         // results are skipped
810         FeaturePtr aSketchFeature = ModelAPI_Feature::feature(anObject);
811         aSketchObjects.append(aSketchFeature);
812       }
813     }
814     // if the selection contains only local selected presentations from other sketches,
815     // the Delete operation should not be done at all
816     if (aSketchObjects.size() == 0)
817       return true;
818
819     // 3. start operation
820     QString aDescription = aWorkshop->contextMenuMgr()->action("DELETE_CMD")->text();
821     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, this);
822
823     // the active nested sketch operation should be aborted unconditionally
824     // the Delete action should be additionally granted for the Sketch operation
825     // in order to do not abort/commit it
826     if (!anOpMgr->canStartOperation(anOpAction->id()))
827       return true; // the objects are processed but can not be deleted
828
829     anOpMgr->startOperation(anOpAction);
830
831     // WORKAROUND, should be done to avoid viewer highlight update after deletetion of objects
832     // the problem is in AIS Dimensions recompute
833     // if a line and the dim are removed, line is the first
834     // it causes the AIS recompute, where the base line is null,
835     // the result is empty AIS in the viewer
836     XGUI_Tools::workshop(myWorkshop)->selector()->clearSelection();
837
838     // 4. delete features
839     // sketch feature should be skipped, only sub-features can be removed
840     // when sketch operation is active
841     aWorkshop->deleteFeatures(aSketchObjects);
842     // 5. stop operation
843     anOpMgr->commitOperation();
844   }
845   return isProcessed;
846 }
847
848 void PartSet_Module::onFeatureTriggered()
849 {
850   // is commented for imp: Unpressing the button of the current action must behave like
851   // a validation if the entity can be created (instead of Cancel, as currently)
852   /*QAction* aCmd = dynamic_cast<QAction*>(sender());
853   if (aCmd->isCheckable() && aCmd->isChecked()) {
854     // 1. check whether the delete should be processed in the module
855     ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
856     bool isNestedOp = myModule->sketchMgr()->isNestedCreateOperation(anOperation);
857     if (isNestedOp) {
858       // in case if in the viewer nothing is displayed, the create operation should not be
859       // comitted even if all values of the feature are initialized
860       if (!mySketchMgr->canDisplayCurrentCreatedFeature()) {
861         // the action information should be saved before the operation is aborted
862         // because this abort leads to update command status, which unchecks this action
863         anOperation->abort();
864         launchOperation(aCmd->data().toString());
865       }
866     }
867   }*/
868   ModuleBase_IModule::onFeatureTriggered();
869 }
870
871 void PartSet_Module::editFeature(FeaturePtr theFeature)
872 {
873   storeConstraintsState(theFeature->getKind());
874   ModuleBase_IModule::editFeature(theFeature);
875 }
876
877 bool PartSet_Module::canCommitOperation() const
878 {
879   return true;
880 }
881
882 void PartSet_Module::launchOperation(const QString& theCmdId)
883 {
884   myIsOperationIsLaunched = true;
885   storeConstraintsState(theCmdId.toStdString());
886   updateConstraintsState(theCmdId.toStdString());
887
888   ModuleBase_IModule::launchOperation(theCmdId);
889
890   myIsOperationIsLaunched = false;
891 }
892
893 void PartSet_Module::storeConstraintsState(const std::string& theFeatureKind)
894 {
895   if (myWorkshop->currentOperation() &&
896       myWorkshop->currentOperation()->id().toStdString() == SketchPlugin_Sketch::ID()) {
897     const QMap<PartSet_Tools::ConstraintVisibleState, bool>& aShownStates =
898                                                   mySketchMgr->showConstraintStates();
899     myHasConstraintShown = aShownStates;
900   }
901 }
902
903 void PartSet_Module::updateConstraintsState(const std::string& theFeatureKind)
904 {
905   if (PartSet_SketcherMgr::constraintsIdList().contains(theFeatureKind.c_str()) ||
906       PartSet_SketcherMgr::replicationsIdList().contains(theFeatureKind.c_str())) {
907     // Show constraints if a constraint was anOperation
908     mySketchMgr->updateBySketchParameters(PartSet_Tools::Geometrical, true);
909     mySketchMgr->updateBySketchParameters(PartSet_Tools::Dimensional, true);
910     mySketchMgr->updateBySketchParameters(PartSet_Tools::Expressions,
911                                           myHasConstraintShown[PartSet_Tools::Expressions]);
912   }
913 }
914
915 void PartSet_Module::onObjectDisplayed(ObjectPtr theObject, AISObjectPtr theAIS)
916 {
917   Handle(AIS_InteractiveObject) anAIS = theAIS->impl<Handle(AIS_InteractiveObject)>();
918   if (!anAIS.IsNull()) {
919     Handle(AIS_InteractiveContext) aCtx = anAIS->GetContext();
920     Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(anAIS);
921     if (!aDim.IsNull()) {
922       aCtx->SetZLayer(aDim, myVisualLayerId);
923     } else {
924       Handle(SketcherPrs_SymbolPrs) aCons = Handle(SketcherPrs_SymbolPrs)::DownCast(anAIS);
925       if (!aCons.IsNull())
926         aCtx->SetZLayer(aCons, myVisualLayerId);
927     }
928   }
929 }
930
931 void PartSet_Module::onBeforeObjectErase(ObjectPtr theObject, AISObjectPtr theAIS)
932 {
933   // this is obsolete
934   // it should be recomputed in order to disappear in the viewer if the corresponded object
935   // is erased
936   //if (myCustomPrs->isActive())
937   //  myCustomPrs->redisplay(theObject, false);
938 }
939
940 void PartSet_Module::onViewTransformed(int theTrsfType)
941 {
942   // Set length of arrows constant in pixel size
943   // if the operation is panning or rotate or panglobal then do nothing
944   if ((theTrsfType == 1) || (theTrsfType == 3) || (theTrsfType == 4))
945     return;
946   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
947   Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
948   if (aContext.IsNull())
949     return;
950
951   //Handle(V3d_View) aView = aViewer->activeView();
952
953   XGUI_Workshop* aWorkshop = getWorkshop();
954   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
955   Handle(V3d_Viewer) aV3dViewer = aContext->CurrentViewer();
956   Handle(V3d_View) aView;
957   double aScale = 0;
958   for (aV3dViewer->InitDefinedViews();
959        aV3dViewer->MoreDefinedViews();
960        aV3dViewer->NextDefinedViews()) {
961     Handle(V3d_View) aV = aV3dViewer->DefinedView();
962     double aS = aV->Scale();
963     if (aS > aScale) {
964       aScale = aS;
965       aView = aV;
966     }
967   }
968   if (aView.IsNull())
969     return;
970   double aLen = aView->Convert(SketcherPrs_Tools::getDefaultArrowSize());
971
972   double aPrevLen = SketcherPrs_Tools::getArrowSize();
973   SketcherPrs_Tools::setArrowSize(aLen);
974   const double aPrevScale = aViewer->Scale(aViewer->activeView());
975   const double aCurScale = aViewer->activeView()->Camera()->Scale();
976   aViewer->SetScale(aViewer->activeView(), aCurScale);
977   SketcherPrs_Tools::setTextHeight (aCurScale / aPrevScale * SketcherPrs_Tools::getTextHeight());
978   bool isModified = false;
979   QList<AISObjectPtr> aPrsList = aDisplayer->displayedPresentations();
980   foreach (AISObjectPtr aAIS, aPrsList) {
981     Handle(AIS_InteractiveObject) aAisObj = aAIS->impl<Handle(AIS_InteractiveObject)>();
982
983     Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(aAisObj);
984     if (!aDim.IsNull()) {
985       aDim->DimensionAspect()->ArrowAspect()->SetLength(aLen);
986       aContext->Redisplay(aDim, false);
987       isModified = true;
988     }
989   }
990   if (isModified)
991     aDisplayer->updateViewer();
992 }
993
994 bool PartSet_Module::isCustomPrsActivated(const ModuleBase_CustomizeFlag& theFlag) const
995 {
996   return myCustomPrs->isActive(theFlag);
997 }
998
999 void PartSet_Module::activateCustomPrs(const FeaturePtr& theFeature,
1000                                        const ModuleBase_CustomizeFlag& theFlag,
1001                                        const bool theUpdateViewer)
1002 {
1003   myCustomPrs->activate(theFeature, theFlag, theUpdateViewer);
1004 }
1005
1006 void PartSet_Module::deactivateCustomPrs(const ModuleBase_CustomizeFlag& theFlag,
1007                                          const bool theUpdateViewer)
1008 {
1009   myCustomPrs->deactivate(theFlag, theUpdateViewer);
1010 }
1011
1012 bool PartSet_Module::customisePresentation(ResultPtr theResult, AISObjectPtr thePrs,
1013                                            std::shared_ptr<GeomAPI_ICustomPrs> theCustomPrs)
1014 {
1015   bool aCustomized = false;
1016
1017   XGUI_Workshop* aWorkshop = getWorkshop();
1018   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1019   ObjectPtr anObject = aDisplayer->getObject(thePrs);
1020   if (!anObject)
1021     return aCustomized;
1022
1023   if (!theResult.get()) {
1024     bool isConflicting = myOverconstraintListener->isConflictingObject(anObject);
1025     // customize sketch symbol presentation
1026     if (thePrs.get()) {
1027       Handle(AIS_InteractiveObject) anAISIO = thePrs->impl<Handle(AIS_InteractiveObject)>();
1028       if (!anAISIO.IsNull()) {
1029         if (!Handle(SketcherPrs_SymbolPrs)::DownCast(anAISIO).IsNull()) {
1030           Handle(SketcherPrs_SymbolPrs) aPrs = Handle(SketcherPrs_SymbolPrs)::DownCast(anAISIO);
1031           if (!aPrs.IsNull()) {
1032             std::vector<int> aColor;
1033             myOverconstraintListener->getConflictingColor(aColor);
1034             aPrs->SetConflictingConstraint(isConflicting, aColor);
1035             aCustomized = true;
1036           }
1037         } else if (!Handle(SketcherPrs_Coincident)::DownCast(anAISIO).IsNull()) {
1038           Handle(SketcherPrs_Coincident) aPrs = Handle(SketcherPrs_Coincident)::DownCast(anAISIO);
1039           if (!aPrs.IsNull()) {
1040             std::vector<int> aColor;
1041             myOverconstraintListener->getConflictingColor(aColor);
1042             aPrs->SetConflictingConstraint(isConflicting, aColor);
1043             aCustomized = true;
1044           }
1045         }
1046       }
1047     }
1048     // customize sketch dimension constraint presentation
1049     if (!aCustomized) {
1050       std::vector<int> aColor;
1051       if (isConflicting) {
1052         myOverconstraintListener->getConflictingColor(aColor);
1053       }
1054       if (aColor.empty())
1055         XGUI_CustomPrs::getDefaultColor(anObject, true, aColor);
1056       if (!aColor.empty()) {
1057         aCustomized = thePrs->setColor(aColor[0], aColor[1], aColor[2]);
1058       }
1059     }
1060   }
1061   // customize dimentional constrains
1062   sketchMgr()->customizePresentation(anObject);
1063
1064   return aCustomized;
1065 }
1066
1067 bool PartSet_Module::customizeObject(ObjectPtr theObject, const ModuleBase_CustomizeFlag& theFlag,
1068                                      const bool theUpdateViewer)
1069 {
1070   bool isRedisplayed = false;
1071   if (myCustomPrs->isActive(theFlag))
1072     isRedisplayed = myCustomPrs->redisplay(theObject, theFlag, theUpdateViewer);
1073
1074   return isRedisplayed;
1075 }
1076
1077 void PartSet_Module::customizeObjectBrowser(QWidget* theObjectBrowser)
1078 {
1079   XGUI_ObjectsBrowser* aOB = dynamic_cast<XGUI_ObjectsBrowser*>(theObjectBrowser);
1080   if (aOB) {
1081     QLabel* aLabel = aOB->activeDocLabel();
1082     aLabel->installEventFilter(myMenuMgr);
1083     connect(aLabel, SIGNAL(customContextMenuRequested(const QPoint&)),
1084           SLOT(onActiveDocPopup(const QPoint&)));
1085     aOB->treeView()->setExpandsOnDoubleClick(false);
1086     connect(aOB->treeView(), SIGNAL(doubleClicked(const QModelIndex&)),
1087       SLOT(onTreeViewDoubleClick(const QModelIndex&)));
1088
1089     Events_Loop* aLoop = Events_Loop::loop();
1090     aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1091   }
1092 }
1093
1094 void PartSet_Module::onActiveDocPopup(const QPoint& thePnt)
1095 {
1096   SessionPtr aMgr = ModelAPI_Session::get();
1097   QAction* aActivatePartAction = myMenuMgr->action("ACTIVATE_PARTSET_CMD");
1098
1099   XGUI_Workshop* aWorkshop = getWorkshop();
1100   QLabel* aHeader = aWorkshop->objectBrowser()->activeDocLabel();
1101
1102   aActivatePartAction->setEnabled((aMgr->activeDocument() != aMgr->moduleDocument()));
1103
1104   QMenu aMenu;
1105   aMenu.addAction(aActivatePartAction);
1106   aMenu.exec(aHeader->mapToGlobal(thePnt));
1107 }
1108
1109 Handle(AIS_InteractiveObject) PartSet_Module::createPresentation(const ResultPtr& theResult)
1110 {
1111   return mySketchMgr->createPresentation(theResult);
1112 }
1113
1114
1115 ObjectPtr PartSet_Module::findPresentedObject(const AISObjectPtr& theAIS) const
1116 {
1117   ObjectPtr anObject;
1118   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1119   if (aOperation) {
1120     /// If last line finished on vertex the lines creation sequence has to be break
1121     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
1122     if (aPanel) {
1123       ModuleBase_ModelWidget* anActiveWidget = aPanel->activeWidget();
1124       // if there is an active widget, find the presented object in it
1125       if (!anActiveWidget)
1126         anActiveWidget = aPanel->preselectionWidget();
1127
1128       ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
1129                                                                              (anActiveWidget);
1130       if (aWidgetValidated)
1131         anObject = aWidgetValidated->findPresentedObject(theAIS);
1132     }
1133   }
1134   return anObject;
1135 }
1136
1137 bool PartSet_Module::canBeShaded(Handle(AIS_InteractiveObject) theAIS) const
1138 {
1139   bool aCanBeShaged = true;
1140
1141   Handle(PartSet_ResultSketchPrs) aPrs = Handle(PartSet_ResultSketchPrs)::DownCast(theAIS);
1142   if (!aPrs.IsNull())
1143     aCanBeShaged = false;
1144
1145   return aCanBeShaged;
1146 }
1147
1148 void PartSet_Module::addObjectBrowserMenu(QMenu* theMenu) const
1149 {
1150   QObjectPtrList aObjects = myWorkshop->selection()->selectedObjects();
1151   int aSelected = aObjects.size();
1152   SessionPtr aMgr = ModelAPI_Session::get();
1153   QAction* aActivatePartAction = myMenuMgr->action("ACTIVATE_PART_CMD");
1154
1155   ModuleBase_Operation* aCurrentOp = myWorkshop->currentOperation();
1156   if (aSelected == 1) {
1157     bool hasResult = false;
1158     bool hasFeature = false;
1159     bool hasParameter = false;
1160     bool hasCompositeOwner = false;
1161     ModuleBase_Tools::checkObjects(aObjects, hasResult, hasFeature, hasParameter,
1162                                    hasCompositeOwner);
1163     ObjectPtr aObject = aObjects.first();
1164     if (aObject) {
1165       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1166       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1167       bool isPart = aPart.get() ||
1168         (aFeature.get() && (aFeature->getKind() == PartSetPlugin_Part::ID()));
1169       if (isPart) {
1170         DocumentPtr aPartDoc;
1171         if (!aPart.get()) {
1172           aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFeature->firstResult());
1173         }
1174         if (aPart.get()) // this may be null is Part feature is disabled
1175           aPartDoc = aPart->partDoc();
1176
1177         theMenu->addAction(aActivatePartAction);
1178         aActivatePartAction->setEnabled((aMgr->activeDocument() != aPartDoc));
1179
1180       } else if (aObject->document() == aMgr->activeDocument()) {
1181         if (hasParameter || hasFeature) {
1182           myMenuMgr->action("EDIT_CMD")->setEnabled(true);
1183           theMenu->addAction(myMenuMgr->action("EDIT_CMD"));
1184           if (aCurrentOp && aFeature.get()) {
1185             if (aCurrentOp->id().toStdString() == aFeature->getKind())
1186               myMenuMgr->action("EDIT_CMD")->setEnabled(false);
1187           }
1188         }
1189       }
1190     }
1191   }
1192   bool aNotDeactivate = (aCurrentOp == 0);
1193   if (!aNotDeactivate) {
1194     aActivatePartAction->setEnabled(false);
1195   }
1196 }
1197
1198 #define EXPAND_PARENT(OBJ) \
1199 QModelIndex aObjIndex = aDataModel->objectIndex(OBJ); \
1200 if (aObjIndex.isValid()) { \
1201   QModelIndex aParent = aObjIndex.parent(); \
1202   int aCount = aDataModel->rowCount(aParent); \
1203   if (aCount == 1) \
1204     aTreeView->setExpanded(aParent, true); \
1205 }
1206
1207
1208 void PartSet_Module::processEvent(const std::shared_ptr<Events_Message>& theMessage)
1209 {
1210   if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_DOCUMENT_CHANGED)) {
1211     // Do not change activation of parts if an operation active
1212     static QStringList aAllowActivationList;
1213     if (aAllowActivationList.isEmpty())
1214       aAllowActivationList <<
1215       QString(PartSetPlugin_Part::ID().c_str()) <<
1216       QString(PartSetPlugin_Duplicate::ID().c_str()) <<
1217       QString(PartSetPlugin_Remove::ID().c_str());
1218     if (myWorkshop->currentOperation() &&
1219       (!aAllowActivationList.contains(myWorkshop->currentOperation()->id())))
1220       return;
1221     XGUI_Workshop* aWorkshop = getWorkshop();
1222     XGUI_DataTree* aTreeView = aWorkshop->objectBrowser()->treeView();
1223     QLabel* aLabel = aWorkshop->objectBrowser()->activeDocLabel();
1224     QPalette aPalet = aLabel->palette();
1225
1226     SessionPtr aMgr = ModelAPI_Session::get();
1227     DocumentPtr aActiveDoc = aMgr->activeDocument();
1228     if (myActivePartIndex.isValid())
1229       aTreeView->setExpanded(myActivePartIndex, false);
1230     XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1231     myActivePartIndex = aDataModel->documentRootIndex(aActiveDoc);
1232     if (myActivePartIndex.isValid())
1233       aTreeView->setExpanded(myActivePartIndex, true);
1234
1235     aLabel->setPalette(aPalet);
1236     aWorkshop->updateCommandStatus();
1237
1238     // Update displayed objects in order to update active color
1239     XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1240     QObjectPtrList aObjects = aDisplayer->displayedObjects();
1241     bool aHidden;
1242     foreach(ObjectPtr aObj, aObjects) {
1243       aHidden = !aObj->data() || !aObj->data()->isValid() ||
1244         aObj->isDisabled() || (!aObj->isDisplayed());
1245       if (!aHidden)
1246         aDisplayer->redisplay(aObj, false);
1247     }
1248     aDisplayer->updateViewer();
1249   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
1250     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
1251         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
1252     std::set<ObjectPtr> aObjects = aUpdMsg->objects();
1253
1254     ObjectPtr aConstrObj;
1255     ObjectPtr aResultObj;
1256     std::set<ObjectPtr>::const_iterator aIt;
1257     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
1258     for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
1259       ObjectPtr aObject = (*aIt);
1260       if ((!aResultObj.get()) && (aObject->groupName() == ModelAPI_ResultBody::group())
1261           && (aObject->document() != aRootDoc))
1262         aResultObj = aObject;
1263       if ((!aConstrObj.get()) && (aObject->groupName() == ModelAPI_ResultConstruction::group())
1264           && (aObject->document() != aRootDoc))
1265         aConstrObj = aObject;
1266       if (aResultObj.get() && aConstrObj.get())
1267         break;
1268     }
1269
1270     if (aResultObj.get() || aConstrObj.get()) {
1271       XGUI_Workshop* aWorkshop = getWorkshop();
1272       XGUI_DataTree* aTreeView = aWorkshop->objectBrowser()->treeView();
1273       XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1274
1275       if (aResultObj.get()) {
1276         EXPAND_PARENT(aResultObj)
1277       }
1278       if (aConstrObj.get()) {
1279         EXPAND_PARENT(aConstrObj)
1280       }
1281     }
1282   }
1283 }
1284
1285 void PartSet_Module::onTreeViewDoubleClick(const QModelIndex& theIndex)
1286 {
1287   if (myWorkshop->currentOperation()) // Do not change activation of parts if an operation active
1288     return;
1289   SessionPtr aMgr = ModelAPI_Session::get();
1290   if (!theIndex.isValid()) {
1291     // It seems that this code is obsolete
1292     //aMgr->setActiveDocument(aMgr->moduleDocument());
1293     return;
1294   }
1295   if (theIndex.column() != 0) // Use only first column
1296     return;
1297
1298   XGUI_Workshop* aWorkshop = getWorkshop();
1299   XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1300   // De not use non editable Indexes
1301   if ((aDataModel->flags(theIndex) & Qt::ItemIsSelectable) == 0)
1302     return;
1303   ObjectPtr aObj = aDataModel->object(theIndex);
1304
1305   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1306   if (!aPart.get()) { // Probably this is Feature
1307     FeaturePtr aPartFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
1308     if (aPartFeature.get() && (aPartFeature->getKind() == PartSetPlugin_Part::ID())) {
1309       aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aPartFeature->firstResult());
1310     }
1311   }
1312   if (aPart.get()) { // if this is a part
1313     if (aPart->partDoc() == aMgr->activeDocument()) {
1314       myMenuMgr->activatePartSet();
1315     } else {
1316       myMenuMgr->activatePart(aPart);
1317     }
1318   }
1319 }
1320
1321
1322 void PartSet_Module::onViewCreated(ModuleBase_IViewWindow*)
1323 {
1324   // z layer is created for all started operations in order to visualize operation AIS presentation
1325   // over the object
1326   Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
1327   if (aContext.IsNull())
1328     return;
1329
1330   Handle(V3d_Viewer) aViewer = aContext->CurrentViewer();
1331   if (myVisualLayerId == 0) {
1332     if (myVisualLayerId == 0)
1333       aViewer->AddZLayer(myVisualLayerId);
1334   } else {
1335     TColStd_SequenceOfInteger aZList;
1336     aViewer->GetAllZLayers(aZList);
1337     bool aFound = false;
1338     for (int i = 1; i <= aZList.Length(); i++) {
1339       if (aZList(i) == myVisualLayerId) {
1340         aFound = true;
1341         break;
1342       }
1343     }
1344     if (!aFound)
1345       aViewer->AddZLayer(myVisualLayerId);
1346   }
1347   // if there is an active operation with validated widget,
1348   // the filters of this widget should be activated in the created view
1349   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1350   if (aOperation) {
1351     ModuleBase_ModelWidget* anActiveWidget = activeWidget();
1352     if (anActiveWidget) {
1353       ModuleBase_WidgetSelector* aWSelector =
1354         dynamic_cast<ModuleBase_WidgetSelector*>(anActiveWidget);
1355       if (aWSelector)
1356         aWSelector->activateSelectionAndFilters(true);
1357     }
1358   }
1359 }
1360
1361 //******************************************************
1362 void PartSet_Module::widgetStateChanged(int thePreviousState)
1363 {
1364   mySketchMgr->widgetStateChanged(thePreviousState);
1365 }
1366
1367 bool PartSet_Module::processEnter(const std::string& thePreviousAttributeID)
1368 {
1369   return mySketchReentrantMgr->processEnter(thePreviousAttributeID);
1370 }
1371
1372 //******************************************************
1373 void PartSet_Module::beforeOperationStopped(ModuleBase_Operation* theOperation)
1374 {
1375   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
1376     mySketchMgr->stopSketch(theOperation);
1377   }
1378 }
1379
1380 //******************************************************
1381 GeomShapePtr PartSet_Module::findShape(const AttributePtr& theAttribute)
1382 {
1383   GeomShapePtr aGeomShape;
1384
1385   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
1386   if (anOperation && sketchMgr()->isNestedSketchOperation(anOperation)) {
1387     aGeomShape = PartSet_Tools::findShapeBy2DPoint(theAttribute, myWorkshop);
1388   }
1389   return aGeomShape;
1390 }
1391
1392 //******************************************************
1393 AttributePtr PartSet_Module::findAttribute(const ObjectPtr& theObject,
1394                                            const GeomShapePtr& theGeomShape)
1395 {
1396   AttributePtr anAttribute;
1397   GeomShapePtr aGeomShape = theGeomShape;
1398   if (!aGeomShape.get()) {
1399     // processing shape of result, e.g. sketch circle center is selected, this is a result
1400     // the geom shape is empty, the shape of result should be used
1401     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1402     if (aResult.get()) {
1403       aGeomShape = aResult->shape();
1404     }
1405   }
1406
1407   if (aGeomShape.get()) {
1408     TopoDS_Shape aTDSShape = aGeomShape->impl<TopoDS_Shape>();
1409     return PartSet_Tools::findAttributeBy2dPoint(theObject, aTDSShape,
1410                                                  mySketchMgr->activeSketch());
1411   }
1412   return anAttribute;
1413 }
1414
1415 //******************************************************
1416 void PartSet_Module::onChoiceChanged(ModuleBase_ModelWidget* theWidget,
1417                                      int theIndex)
1418 {
1419   PartSet_WidgetChoice* aChoiceWidget = dynamic_cast<PartSet_WidgetChoice*>(theWidget);
1420   if (!aChoiceWidget)
1421     return;
1422
1423   QString aChoiceTitle = aChoiceWidget->getPropertyPanelTitle(theIndex);
1424   if (!aChoiceTitle.isEmpty()) {
1425     ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1426     if (!aOperation)
1427       return;
1428     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
1429     if (aPanel)
1430       aPanel->setWindowTitle(aChoiceTitle);
1431   }
1432 }
1433
1434 //******************************************************
1435 XGUI_Workshop* PartSet_Module::getWorkshop() const
1436 {
1437   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
1438   return aConnector->workshop();
1439 }
1440
1441 //******************************************************
1442 void PartSet_Module::setDefaultConstraintShown()
1443 {
1444   myHasConstraintShown[PartSet_Tools::Geometrical] = true;
1445   myHasConstraintShown[PartSet_Tools::Dimensional] = true;
1446   myHasConstraintShown[PartSet_Tools::Expressions] = false;
1447 }