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