Salome HOME
Merge branch 'V9_5_BR'
[modules/shaper.git] / src / PartSet / PartSet_Module.cpp
1 // Copyright (C) 2014-2020  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include "PartSet_Module.h"
21 #include "PartSet_WidgetSketchLabel.h"
22 #include "PartSet_Validators.h"
23 #include "PartSet_Tools.h"
24 #include "PartSet_PreviewPlanes.h"
25 #include "PartSet_WidgetBSplinePoints.h"
26 #include "PartSet_WidgetPoint2d.h"
27 #include "PartSet_WidgetPoint2DFlyout.h"
28 #include "PartSet_WidgetShapeSelector.h"
29 #include "PartSet_WidgetMultiSelector.h"
30 #include "PartSet_WidgetFeaturePointSelector.h"
31 #include "PartSet_WidgetEditor.h"
32 #include "PartSet_WidgetFileSelector.h"
33 #include "PartSet_WidgetSketchCreator.h"
34 #include "PartSet_SketcherMgr.h"
35 #include "PartSet_SketcherReentrantMgr.h"
36 #include "PartSet_ResultSketchPrs.h"
37 #include "PartSet_MenuMgr.h"
38 #include "PartSet_CustomPrs.h"
39 #include "PartSet_IconFactory.h"
40 #include "PartSet_OverconstraintListener.h"
41 #include "PartSet_TreeNodes.h"
42 #include "PartSet_FieldStepPrs.h"
43 #include "PartSet_BSplineWidget.h"
44
45 #include "PartSet_Filters.h"
46 #include "PartSet_FilterInfinite.h"
47
48 #ifdef _DEBUG
49 #include <QDebug>
50 #endif
51
52 #include <PartSetPlugin_Remove.h>
53 #include <PartSetPlugin_Part.h>
54 #include <PartSetPlugin_Duplicate.h>
55
56 #include <SketchPlugin_ConstraintCoincidence.h>
57
58 #include <ModuleBase_Operation.h>
59 #include <ModuleBase_IViewer.h>
60 #include <ModuleBase_IViewWindow.h>
61 #include <ModuleBase_IPropertyPanel.h>
62 #include <ModuleBase_ISelectionActivate.h>
63 #include <ModuleBase_WidgetChoice.h>
64 #include <ModuleBase_WidgetEditor.h>
65 #include <ModuleBase_WidgetValidated.h>
66 #include <ModuleBase_Tools.h>
67 #include <ModuleBase_OperationFeature.h>
68 #include <ModuleBase_WidgetFactory.h>
69 #include <ModuleBase_OperationDescription.h>
70 #include <ModuleBase_ViewerPrs.h>
71 #include <ModuleBase_ResultPrs.h>
72
73 #include <ModelAPI_ResultField.h>
74 #include <ModelAPI_Object.h>
75 #include <ModelAPI_Events.h>
76 #include <ModelAPI_Validator.h>
77 #include <ModelAPI_Data.h>
78 #include <ModelAPI_Session.h>
79 #include <ModelAPI_ResultBody.h>
80 #include <ModelAPI_AttributeString.h>
81 #include <ModelAPI_AttributeSelectionList.h>
82 #include <ModelAPI_Tools.h>
83 #include <ModelAPI_ResultConstruction.h>
84 #include <ModelAPI_AttributeIntArray.h>
85 #include <ModelAPI_ResultGroup.h>
86
87 #include <GeomDataAPI_Point2D.h>
88 #include <GeomDataAPI_Point.h>
89 #include <GeomDataAPI_Dir.h>
90
91 #include <XGUI_ActiveControlMgr.h>
92 #include <XGUI_ActiveControlSelector.h>
93 #include <XGUI_ActionsMgr.h>
94 #include <XGUI_ContextMenuMgr.h>
95 #include <XGUI_DataModel.h>
96 #include <XGUI_Displayer.h>
97 #include <XGUI_ErrorMgr.h>
98 #include <XGUI_FacesPanelSelector.h>
99 #include <XGUI_ModuleConnector.h>
100 #include <XGUI_ObjectsBrowser.h>
101 #include <XGUI_OperationMgr.h>
102 #include <XGUI_PropertyPanel.h>
103 #include <XGUI_SelectionMgr.h>
104 #include <XGUI_Tools.h>
105 #include <XGUI_Workshop.h>
106
107 #include <SketchPlugin_ConstraintAngle.h>
108 #include <SketchPlugin_ConstraintLength.h>
109 #include <SketchPlugin_ConstraintDistance.h>
110 #include <SketchPlugin_ConstraintParallel.h>
111 #include <SketchPlugin_ConstraintPerpendicular.h>
112 #include <SketchPlugin_ConstraintRadius.h>
113 #include <SketchPlugin_Feature.h>
114 #include <SketchPlugin_Projection.h>
115 #include <SketchPlugin_Sketch.h>
116
117 #include <SketcherPrs_SymbolPrs.h>
118 #include <SketcherPrs_PositionMgr.h>
119 #include <SketcherPrs_Coincident.h>
120 #include <SketcherPrs_Tools.h>
121
122 #include <Events_Loop.h>
123 #include <Config_PropManager.h>
124 #include <Config_Keywords.h>
125
126 #include <AIS_Dimension.hxx>
127 #include <AIS_InteractiveObject.hxx>
128 #include <StdSelect_TypeOfFace.hxx>
129 #include <TopoDS_Vertex.hxx>
130 #include <TopoDS.hxx>
131 #include <TopoDS_Shape.hxx>
132 #include <BRep_Tool.hxx>
133
134 #include <QObject>
135 #include <QMouseEvent>
136 #include <QString>
137 #include <QTimer>
138 #include <QApplication>
139 #include <QMessageBox>
140 #include <QMainWindow>
141 #include <QLineEdit>
142 #include <QString>
143
144 #include <GeomAlgoAPI_FaceBuilder.h>
145 #include <GeomDataAPI_Dir.h>
146
147 #include <SelectMgr_ListIteratorOfListOfFilter.hxx>
148
149 #define FEATURE_ITEM_COLOR "0,0,225"
150
151
152 /*!Create and return new instance of XGUI_Module*/
153 extern "C" PARTSET_EXPORT ModuleBase_IModule* createModule(ModuleBase_IWorkshop* theWshop)
154 {
155   return new PartSet_Module(theWshop);
156 }
157
158 //******************************************************
159 PartSet_Module::PartSet_Module(ModuleBase_IWorkshop* theWshop)
160 : ModuleBase_IModule(theWshop),
161   myIsOperationIsLaunched(false),
162   myVisualLayerId(0),
163   myRoot(0)
164 {
165   new PartSet_IconFactory(this);
166
167   mySketchMgr = new PartSet_SketcherMgr(this);
168   mySketchReentrantMgr = new PartSet_SketcherReentrantMgr(theWshop);
169
170   ModuleBase_IViewer* aViewer = theWshop->viewer();
171   connect(aViewer, SIGNAL(keyRelease(ModuleBase_IViewWindow*, QKeyEvent*)),
172           this, SLOT(onKeyRelease(ModuleBase_IViewWindow*, QKeyEvent*)));
173   connect(aViewer, SIGNAL(viewTransformed(int)),
174           SLOT(onViewTransformed(int)));
175   connect(aViewer, SIGNAL(viewCreated(ModuleBase_IViewWindow*)),
176           SLOT(onViewCreated(ModuleBase_IViewWindow*)));
177   myMenuMgr = new PartSet_MenuMgr(this);
178   myCustomPrs = new PartSet_CustomPrs(theWshop);
179
180   myOverconstraintListener = new PartSet_OverconstraintListener(theWshop);
181
182   Events_Loop* aLoop = Events_Loop::loop();
183   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_DOCUMENT_CHANGED));
184   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
185
186   registerSelectionFilter(SF_GlobalFilter, new PartSet_GlobalFilter(myWorkshop));
187   registerSelectionFilter(SF_FilterInfinite, new PartSet_FilterInfinite(myWorkshop));
188   Handle(PartSet_ResultGroupNameFilter) aCRFilter = new PartSet_ResultGroupNameFilter(myWorkshop);
189   std::set<std::string> aCRGroupNames;
190   aCRGroupNames.insert(ModelAPI_ResultConstruction::group());
191   aCRFilter->setGroupNames(aCRGroupNames);
192   registerSelectionFilter(SF_ResultGroupNameFilter, aCRFilter);
193
194   setDefaultConstraintShown();
195
196   //Config_PropManager::registerProp("Visualization", "object_default_color", "Object color",
197   //                                 Config_Prop::Color, "225,225,225");
198
199   Config_PropManager::registerProp("Visualization", "result_body_color", "Result color",
200     Config_Prop::Color, ModelAPI_ResultBody::DEFAULT_COLOR());
201
202   Config_PropManager::registerProp("Visualization", "result_group_color", "Group color",
203     Config_Prop::Color, ModelAPI_ResultGroup::DEFAULT_COLOR());
204
205   Config_PropManager::registerProp("Visualization", "result_construction_color",
206     "Construction color",
207     Config_Prop::Color,
208     ModelAPI_ResultConstruction::DEFAULT_COLOR());
209
210   Config_PropManager::registerProp("Visualization", "result_part_color", "Part color",
211     Config_Prop::Color, ModelAPI_ResultPart::DEFAULT_COLOR());
212
213   Config_PropManager::registerProp("Visualization", "result_field_color", "Field color",
214     Config_Prop::Color, ModelAPI_ResultField::DEFAULT_COLOR());
215
216   Config_PropManager::registerProp("Visualization", "operation_parameter_color",
217                           "Reference shape wireframe color in operation", Config_Prop::Color,
218                           PartSet_CustomPrs::OPERATION_PARAMETER_COLOR());
219   Config_PropManager::registerProp("Visualization", "operation_result_color",
220                           "Result shape wireframe color in operation", Config_Prop::Color,
221                           PartSet_CustomPrs::OPERATION_RESULT_COLOR());
222   Config_PropManager::registerProp("Visualization", "operation_highlight_color",
223                           "Multi selector item color in operation", Config_Prop::Color,
224                           PartSet_CustomPrs::OPERATION_HIGHLIGHT_COLOR());
225   Config_PropManager::registerProp("Visualization", "operation_remove_feature_color",
226                           "Color of removed feature in operation", Config_Prop::Color,
227                           PartSet_CustomPrs::OPERATION_REMOVE_FEATURE_COLOR());
228   Config_PropManager::registerProp("Visualization", "sketch_preview_plane",
229                           "Color of sketch plane", Config_Prop::Color,
230                           PartSet_CustomPrs::OPERATION_SKETCH_PLANE());
231
232   Config_PropManager::registerProp("Visualization", "hidden_face_transparency",
233                                    "Hidden faces transparency",
234                                    Config_Prop::DblSpin,
235                                    "0.8");
236   std::ostringstream aStream;
237   aStream << SketcherPrs_Tools::getDefaultArrowSize();
238   Config_PropManager::registerProp("Visualization", "dimension_arrow_size",
239     "Dimension arrow size", Config_Prop::IntSpin, aStream.str());
240
241   Config_PropManager::registerProp("Visualization", "dimension_font", "Dimension font",
242     Config_Prop::String, "Times-bold");
243
244   aStream.str("");
245   aStream.clear();
246   aStream << SketcherPrs_Tools::getDefaultTextHeight();
247   Config_PropManager::registerProp("Visualization", "dimension_value_size",
248     "Dimension value size", Config_Prop::IntSpin, aStream.str());
249
250   Config_PropManager::registerProp("Visualization", "sketch_dimension_color",
251     "Dimension color",
252     Config_Prop::Color, SKETCH_DIMENSION_COLOR);
253
254   Config_PropManager::registerProp("Visualization", "feature_objectbrowser_color",
255     "Feature items in Object Browser",
256     Config_Prop::Color, FEATURE_ITEM_COLOR);
257
258   Config_PropManager::registerProp("Shortcuts", "add_parameter_shortcut",
259     "Add parameter in parameters manager dialog",
260     Config_Prop::Shortcut, "Ctrl+A");
261
262   Config_PropManager::registerProp("Windows", "use_hide_faces_panel",
263     "Use HideFaces panel in operations", Config_Prop::Boolean, "false");
264 }
265
266 //******************************************************
267 PartSet_Module::~PartSet_Module()
268 {
269   delete myCustomPrs;
270   delete myOverconstraintListener;
271   delete myRoot;
272 }
273
274 //******************************************************
275 void PartSet_Module::createFeatures()
276 {
277   ModuleBase_IModule::createFeatures();
278   myRoot = new PartSet_RootNode();
279   myRoot->setWorkshop(workshop());
280 }
281
282
283 //******************************************************
284 void PartSet_Module::storeSelection()
285 {
286   // cash is used only to restore selection, so it should be filled in storeSelection and
287   // after applying immediatelly cleared in restoreSelection
288   myCurrentSelection.clear();
289   sketchMgr()->storeSelection(PartSet_SketcherMgr::ST_SelectType, myCurrentSelection);
290 }
291
292 //******************************************************
293 void PartSet_Module::restoreSelection()
294 {
295   // cash is used only to restore selection, so it should be filled in storeSelection and
296   // after applying immediatelly cleared in restoreSelection
297   sketchMgr()->restoreSelection(myCurrentSelection);
298   myCurrentSelection.clear();
299 }
300
301 //******************************************************
302 void PartSet_Module::registerValidators()
303 {
304   //Registering of validators
305   SessionPtr aMgr = ModelAPI_Session::get();
306   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
307   aFactory->registerValidator("PartSet_DistanceSelection", new PartSet_DistanceSelection);
308   aFactory->registerValidator("PartSet_LengthSelection", new PartSet_LengthSelection);
309   aFactory->registerValidator("PartSet_PerpendicularSelection", new PartSet_PerpendicularSelection);
310   aFactory->registerValidator("PartSet_ParallelSelection", new PartSet_ParallelSelection);
311   aFactory->registerValidator("PartSet_RadiusSelection", new PartSet_RadiusSelection);
312   aFactory->registerValidator("PartSet_RigidSelection", new PartSet_RigidSelection);
313   aFactory->registerValidator("PartSet_CoincidentSelection", new PartSet_CoincidentSelection);
314   aFactory->registerValidator("PartSet_HVDirSelection", new PartSet_HVDirSelection);
315   aFactory->registerValidator("PartSet_TangentSelection", new PartSet_TangentSelection);
316   aFactory->registerValidator("PartSet_FilletSelection", new PartSet_FilletSelection);
317   aFactory->registerValidator("PartSet_AngleSelection", new PartSet_AngleSelection);
318   aFactory->registerValidator("PartSet_EqualSelection", new PartSet_EqualSelection);
319   aFactory->registerValidator("PartSet_CollinearSelection", new PartSet_CollinearSelection);
320   aFactory->registerValidator("PartSet_MiddlePointSelection", new PartSet_MiddlePointSelection);
321   aFactory->registerValidator("PartSet_DifferentObjects", new PartSet_DifferentObjectsValidator);
322   aFactory->registerValidator("PartSet_DifferentPoints", new PartSet_DifferentPointsValidator);
323   aFactory->registerValidator("PartSet_CoincidentAttr", new PartSet_CoincidentAttr);
324   aFactory->registerValidator("PartSet_MultyTranslationSelection",
325     new PartSet_MultyTranslationSelection);
326   aFactory->registerValidator("PartSet_SplitSelection", new PartSet_SplitSelection);
327   aFactory->registerValidator("PartSet_ProjectionSelection", new PartSet_ProjectionSelection);
328   aFactory->registerValidator("PartSet_IntersectionSelection", new PartSet_IntersectionSelection);
329 }
330
331 //******************************************************
332 void PartSet_Module::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget,
333                                             const bool isToConnect)
334 {
335   mySketchMgr->connectToPropertyPanel(theWidget, isToConnect);
336 }
337
338 //******************************************************
339 void PartSet_Module::operationCommitted(ModuleBase_Operation* theOperation)
340 {
341   if (sketchMgr()->isNestedSketchOperation(theOperation)) {
342     mySketchMgr->commitNestedSketch(theOperation);
343   }
344   /// deactivate of overconstraint listener should be performed after Sketch commit (#2176)
345   if (PartSet_SketcherMgr::isSketchOperation(theOperation))
346     overconstraintListener()->setActive(false);
347
348   /// Restart sketcher operations automatically
349   if (!mySketchReentrantMgr->operationCommitted(theOperation)) {
350     getWorkshop()->selector()->clearSelection();
351   }
352 }
353
354 //******************************************************
355 void PartSet_Module::operationAborted(ModuleBase_Operation* theOperation)
356 {
357   /// Restart sketcher operations automatically
358   mySketchReentrantMgr->operationAborted(theOperation);
359   /// deactivate of overconstraint listener should be performed after Sketch abort (#2176)
360   if (PartSet_SketcherMgr::isSketchOperation(theOperation))
361     overconstraintListener()->setActive(false);
362
363   getWorkshop()->selector()->clearSelection();
364 }
365
366 //******************************************************
367 void PartSet_Module::operationStarted(ModuleBase_Operation* theOperation)
368 {
369   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
370                                                                                 (theOperation);
371   if (aFOperation) {
372     XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(workshop());
373     XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
374
375     ModuleBase_ModelWidget* aFilledWidget = 0;
376     bool aPostonedWidgetActivation = false;
377
378     FeaturePtr aFeature = aFOperation->feature();
379     /// Restart sketcher operations automatically
380     /// it is important to call method of sketch reentrant manager before filling of PP
381     /// because it fills some created feature attributes, these new values should be used
382     /// to fill the property panel
383     mySketchReentrantMgr->operationStarted(theOperation);
384
385     aWorkshop->fillPropertyPanel(aFOperation);
386     // filling the operation values by the current selection
387     // if the operation can be committed after the controls filling, the method perform should
388     // be stopped. Otherwise unnecessary presentations can be shown(e.g. operation prs in sketch)
389     bool isOperationCommitted = false;
390     if (!aFOperation->isEditOperation()) {
391       std::string aGreedAttributeId = ModuleBase_Tools::findGreedAttribute(workshop(), aFeature);
392       // if there is a greed attribute, automatic commit by preselection
393       // for this feature is prohibited
394       aFilledWidget = aFOperation->activateByPreselection(aGreedAttributeId);
395       if (currentOperation() != aFOperation)
396         isOperationCommitted = true;
397       else {
398         if (aGreedAttributeId.empty()) {
399           // a signal should be emitted before the next widget activation
400           // because, the activation of the next widget will give a focus to the widget.
401           // As a result the value of the widget is initialized.
402           // And commit may happens until the value is entered.
403           if (aFilledWidget) {
404             if (mySketchReentrantMgr->canBeCommittedByPreselection())
405               isOperationCommitted = mySketchMgr->operationActivatedByPreselection();
406             // activate the next obligatory widget
407             if (!isOperationCommitted)
408               aPropertyPanel->activateNextWidget(aFilledWidget);
409           }
410         }
411         else { // there is a greed widget
412           const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
413           std::string aFirstAttributeId = aWidgets.front()->attributeID();
414           // activate next widget after greeded if it is the first widget in the panel
415           // else the first panel widget is already activated by operation start
416           if (aFirstAttributeId == aGreedAttributeId)
417             aPostonedWidgetActivation = true;
418         }
419       }
420     } if (!isOperationCommitted) {
421       aWorkshop->connectToPropertyPanel(true);
422       updateSketcherOnStart(aFOperation);
423       updatePresentationsOnStart(aFOperation);
424
425       // the objects of the current operation should be deactivated
426       QObjectPtrList anObjects;
427       anObjects.append(aFeature);
428       std::list<ResultPtr> aResults;
429       ModelAPI_Tools::allResults(aFeature, aResults);
430       std::list<ResultPtr>::const_iterator aIt;
431       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
432         anObjects.append(*aIt);
433       }
434       QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
435       for (; anIt != aLast; anIt++)
436         aWorkshop->deactivateActiveObject(*anIt, false);
437       if (anObjects.size() > 0) {
438         XGUI_Displayer* aDisplayer = aWorkshop->displayer();
439         aDisplayer->updateViewer();
440       }
441       /// state of command actions should be updated after displayed objects modification because
442       /// deactivation(for example) of objects may influence on selection in the viewer
443       /// State of command actions may depend on selection in the viewer(e.g. Sketch)
444       workshop()->updateCommandStatus();
445     }
446     if (aPostonedWidgetActivation) {
447       // if the widget is an empty in the chain of activated widgets, the current operation
448       // is restarted. It should be performed after functionality of the operation starting
449       aPropertyPanel->activateNextWidget(aFilledWidget);
450     }
451   }
452 }
453
454 //******************************************************
455 void PartSet_Module::updateSketcherOnStart(ModuleBase_Operation* theOperation)
456 {
457   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
458     mySketchMgr->startSketch(theOperation);
459   }
460   // It is switched off because of
461   // Task #3067: 5.2.2 Drawing in the sketcher: change the mouse cursor arrow
462   else if (sketchMgr()->isNestedSketchOperation(theOperation)) {
463     mySketchMgr->startNestedSketch(theOperation);
464   }
465 }
466
467 //******************************************************
468 void PartSet_Module::updatePresentationsOnStart(ModuleBase_Operation* theOperation)
469 {
470   ModuleBase_OperationFeature* aFOperation =
471     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
472   if (aFOperation) {
473     myCustomPrs->activate(aFOperation->feature(), ModuleBase_IModule::CustomizeArguments, false);
474     myCustomPrs->activate(aFOperation->feature(), ModuleBase_IModule::CustomizeResults, false);
475   }
476 }
477
478 //******************************************************
479 void PartSet_Module::operationResumed(ModuleBase_Operation* theOperation)
480 {
481   ModuleBase_IModule::operationResumed(theOperation);
482
483   ModuleBase_OperationFeature* aFOperation =
484     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
485   if (aFOperation) {
486     myCustomPrs->activate(aFOperation->feature(), ModuleBase_IModule::CustomizeArguments, false);
487     myCustomPrs->activate(aFOperation->feature(), ModuleBase_IModule::CustomizeResults, false);
488   }
489 }
490
491 //******************************************************
492 void PartSet_Module::operationStopped(ModuleBase_Operation* theOperation)
493 {
494   bool isModifiedArgs = myCustomPrs->deactivate(ModuleBase_IModule::CustomizeArguments, false);
495   bool isModifiedResults = myCustomPrs->deactivate(ModuleBase_IModule::CustomizeResults, false);
496   bool isModified = isModifiedArgs || isModifiedResults;
497
498   if (sketchMgr()->isNestedSketchOperation(theOperation)) {
499     mySketchMgr->stopNestedSketch(theOperation);
500   }
501   else if (PartSet_SketcherMgr::isSketchOperation(theOperation))
502     setDefaultConstraintShown();
503
504   //VSV: Viewer is updated on feature update and redisplay
505   if (isModified) {
506     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myWorkshop);
507     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
508     aDisplayer->updateViewer();
509   }
510
511   QMap<PartSet_Tools::ConstraintVisibleState, bool>::const_iterator
512     anIt = myHasConstraintShown.begin(), aLast = myHasConstraintShown.end();
513   for (; anIt != aLast; anIt++) {
514     mySketchMgr->updateBySketchParameters(anIt.key(), anIt.value());
515   }
516 }
517
518 //******************************************************
519 ModuleBase_Operation* PartSet_Module::currentOperation() const
520 {
521   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
522   XGUI_OperationMgr* anOpMgr = aConnector->workshop()->operationMgr();
523   return anOpMgr->currentOperation();
524 }
525
526 //******************************************************
527 bool PartSet_Module::canUndo() const
528 {
529   bool aCanUndo = false;
530   SessionPtr aMgr = ModelAPI_Session::get();
531   if (aMgr->hasModuleDocument() && aMgr->canUndo()) {
532     aCanUndo = !aMgr->isOperation();
533     if (!aCanUndo) // check the enable state additionally by sketch manager
534       aCanUndo = aMgr->canUndo();
535   }
536   return aCanUndo;
537 }
538
539 //******************************************************
540 bool PartSet_Module::canRedo() const
541 {
542   bool aCanRedo = false;
543   SessionPtr aMgr = ModelAPI_Session::get();
544   if (aMgr->hasModuleDocument() && aMgr->canRedo()) {
545     aCanRedo = !aMgr->isOperation();
546     if (!aCanRedo) // check the enable state additionally by sketch manager
547       aCanRedo = aMgr->canRedo();
548   }
549   return aCanRedo;
550 }
551
552 //******************************************************
553 bool PartSet_Module::canApplyAction(const ObjectPtr& theObject, const QString& theActionId) const
554 {
555   bool aValid = true;
556   if (theActionId == "MOVE_CMD" || theActionId == "MOVE_SPLIT_CMD") {
557     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
558     if (aFeature) {
559       ResultPtr aResult = ModuleBase_Tools::firstResult(aFeature);
560       // part features can not be moved in the history.
561       if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group())
562         aValid = false;
563     }
564   }
565   return aValid;
566 }
567
568 //******************************************************
569 bool PartSet_Module::canEraseObject(const ObjectPtr& theObject) const
570 {
571   // the sketch manager put the restriction to the objects erase
572   return mySketchMgr->canEraseObject(theObject);
573 }
574
575 //******************************************************
576 bool PartSet_Module::canDisplayObject(const ObjectPtr& theObject) const
577 {
578   // the sketch manager put the restriction to the objects display
579   return mySketchMgr->canDisplayObject(theObject);
580 }
581
582 //******************************************************
583 bool PartSet_Module::canUsePreselection(const QString& thePreviousOperationKind,
584                                         const QString& theStartedOperationKind)
585 {
586   if (ModuleBase_IModule::canUsePreselection(thePreviousOperationKind, theStartedOperationKind))
587     return true;
588
589   return mySketchMgr->isNestedSketchFeature(theStartedOperationKind);
590 }
591
592 /*void PartSet_Module::processHiddenObject(const std::list<ObjectPtr>& theObjects)
593 {
594   mySketchMgr->processHiddenObject(theObjects);
595 }*/
596
597 //******************************************************
598 bool PartSet_Module::canActivateSelection(const ObjectPtr& theObject) const
599 {
600   bool aCanActivate = ModuleBase_IModule::canActivateSelection(theObject);
601
602   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
603   bool isSketchOp = PartSet_SketcherMgr::isSketchOperation(anOperation),
604        isNestedOp = sketchMgr()->isNestedSketchOperation(anOperation);
605   if (isSketchOp || isNestedOp) {
606     // in active sketch operation it is possible to activate operation object in selection
607     // in the edit operation, e.g. points of the line can be moved when the line is edited
608     ModuleBase_OperationFeature* aFOperation =
609       dynamic_cast<ModuleBase_OperationFeature*>(anOperation);
610     aCanActivate = aCanActivate || (aFOperation && aFOperation->isEditOperation());
611   }
612   return aCanActivate;
613 }
614
615 //******************************************************
616 bool PartSet_Module::addViewerMenu(const QMap<QString, QAction*>& theStdActions,
617                                    QWidget* theParent,
618                                    QMap<int, QAction*>& theMenuActions) const
619 {
620   return myMenuMgr->addViewerMenu(theStdActions, theParent, theMenuActions);
621 }
622
623 //******************************************************
624 void PartSet_Module::updateViewerMenu(const QMap<QString, QAction*>& theStdActions)
625 {
626   myMenuMgr->updateViewerMenu(theStdActions);
627 }
628
629 //******************************************************
630 bool PartSet_Module::isActionEnableStateFixed(const int theActionId) const
631 {
632   bool isEnabledFixed = false;
633   if (theActionId == XGUI_ActionsMgr::AcceptAll &&
634       mySketchReentrantMgr->isInternalEditActive())
635     isEnabledFixed = true;
636   return isEnabledFixed;
637 }
638
639 //******************************************************
640 QString PartSet_Module::getFeatureError(const FeaturePtr& theFeature)
641 {
642   QString anError = ModuleBase_IModule::getFeatureError(theFeature);
643   if (anError.isEmpty())
644     anError = sketchMgr()->getFeatureError(theFeature);
645
646   return anError;
647 }
648
649 //******************************************************
650 void PartSet_Module::grantedOperationIds(ModuleBase_Operation* theOperation,
651                                          QStringList& theIds) const
652 {
653   myMenuMgr->grantedOperationIds(theOperation, theIds);
654
655   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
656     XGUI_Workshop* aWorkshop = getWorkshop();
657     theIds.append(aWorkshop->contextMenuMgr()->action("DELETE_CMD")->text());
658   }
659 }
660
661 //******************************************************
662 void PartSet_Module::activeSelectionModes(QIntList& theModes)
663 {
664   if (mySketchMgr->activeSketch().get())
665     PartSet_SketcherMgr::sketchSelectionModes(mySketchMgr->activeSketch(), theModes);
666   else
667     theModes = XGUI_Tools::workshop(myWorkshop)->viewerSelectionModes();
668 }
669
670 //******************************************************
671 void PartSet_Module::moduleSelectionModes(int theModesType, QIntList& theModes)
672 {
673   customSubShapesSelectionModes(theModes);
674   //theModes.append(XGUI_Tools::workshop(myWorkshop)->viewerSelectionModes());
675   //myWorkshop->module()->activeSelectionModes(theModes);
676 }
677
678 //******************************************************
679 void PartSet_Module::moduleSelectionFilters(const QIntList& theFilterTypes,
680                                             SelectMgr_ListOfFilter& theSelectionFilters)
681 {
682   bool isSketchActive = mySketchMgr->activeSketch().get();
683
684   std::map<ModuleBase_SelectionFilterType, Handle(SelectMgr_Filter)>::const_iterator aFiltersIt =
685     mySelectionFilters.begin();
686   for (; aFiltersIt != mySelectionFilters.end(); aFiltersIt++) {
687     int aFilterType = aFiltersIt->first;
688     // do not add not participating filters in given parameters
689     if (!theFilterTypes.contains(aFilterType))
690       continue;
691
692     // using sketch filters only if sketch operation is active
693     if (!isSketchActive &&
694         mySketchMgr->sketchSelectionFilter((ModuleBase_SelectionFilterType)aFilterType))
695       continue;
696
697     // using filtering of construction results only from faces panel
698     if (aFilterType == SF_ResultGroupNameFilter)
699       continue;
700
701     theSelectionFilters.Append(aFiltersIt->second);
702   }
703 }
704
705 //******************************************************
706 void PartSet_Module::customSubShapesSelectionModes(QIntList& theModes)
707 {
708   if (theModes.contains(TopAbs_FACE))
709     theModes.append(SketcherPrs_Tools::Sel_Sketch_Face);
710   if (theModes.contains(TopAbs_WIRE))
711     theModes.append(SketcherPrs_Tools::Sel_Sketch_Wire);
712
713   if (mySketchMgr->activeSketch().get())
714     PartSet_SketcherMgr::sketchSelectionModes(mySketchMgr->activeSketch(), theModes);
715 }
716
717 //******************************************************
718 void PartSet_Module::getGeomSelection(const std::shared_ptr<ModuleBase_ViewerPrs>& theSelected,
719                                       ObjectPtr& theObject, AttributePtr& theAttribute)
720 {
721   ObjectPtr anObject = theSelected->object();
722   GeomShapePtr aShape = theSelected->shape();
723
724   theAttribute = findAttribute(anObject, aShape);
725   // TODO: try to create result if object is an external object
726   theObject = anObject;
727 }
728
729 //******************************************************
730 bool PartSet_Module::isMouseOverWindow()
731 {
732   return mySketchMgr->isMouseOverWindow();
733 }
734
735 //******************************************************
736 bool PartSet_Module::isSketchNeutralPointActivated() const
737 {
738   bool isNeutralPoint = true;
739   if (sketchReentranceMgr()->isInternalEditActive())
740     isNeutralPoint = false;
741   if (myIsOperationIsLaunched)
742     isNeutralPoint = false;
743
744   return isNeutralPoint;
745 }
746
747 //******************************************************
748 void PartSet_Module::closeDocument()
749 {
750   myActivePartIndex = QModelIndex();
751   SketcherPrs_PositionMgr::get()->clearAll();
752 }
753
754 //******************************************************
755 void PartSet_Module::clearViewer()
756 {
757   myCustomPrs->clearPrs();
758
759   XGUI_Workshop* aWorkshop = getWorkshop();
760   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
761   aDisplayer->deactivateSelectionFilters(false);
762 }
763
764 //******************************************************
765 void PartSet_Module::propertyPanelDefined(ModuleBase_Operation* theOperation)
766 {
767   ModuleBase_OperationFeature* aFOperation =
768     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
769   if (!aFOperation)
770     return;
771
772   ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
773   // we have to manually activate the sketch label in edit mode
774   if (PartSet_SketcherMgr::isSketchOperation(aFOperation) &&  (aFOperation->isEditOperation()))
775     aPanel->activateWidget(aPanel->modelWidgets().first());
776 }
777
778 //******************************************************
779 bool PartSet_Module::createWidgets(const FeaturePtr& theFeature, const QString& theXmlRepr,
780                                    QList<ModuleBase_ModelWidget*>& theWidgets) const
781 {
782   bool aProcessed = false;
783
784   XGUI_Workshop* aWorkshop = getWorkshop();
785   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
786   if (mySketchMgr->activeSketch().get() && aPropertyPanel) {
787     ModuleBase_ISelection* aSelection = workshop()->selection();
788     // click on a point in sketch leads here with the point is highlighted, not yet selected
789     QList<ModuleBase_ViewerPrsPtr> aPreselection = aSelection->getHighlighted();
790     if (aPreselection.size() == 1) {
791       ModuleBase_ViewerPrsPtr aSelectedPrs = aPreselection[0];
792       ObjectPtr anObject = aSelectedPrs->object();
793
794       FeaturePtr aFeature = ModelAPI_Feature::feature(anObject);
795       GeomShapePtr aShape = aSelectedPrs->shape();
796       // click on the digit of dimension constrain comes here
797       // with an empty shape, so we need the check
798       if (aFeature == theFeature && aShape.get() && !aShape->isNull()) {
799         // if feature has only one result and shape of result is equal to selected shape
800         // this attribute is not processed. It is a case of Sketch Point.
801         if (aFeature->results().size() == 1) {
802           ResultPtr aResult = aFeature->results().front();
803           if (aResult.get() && aResult->shape()->isEqual(aShape))
804             return aProcessed;
805         }
806         const TopoDS_Shape& aTDShape = aShape->impl<TopoDS_Shape>();
807         std::pair<AttributePtr, int> anAttribute =
808             PartSet_Tools::findAttributeBy2dPoint(anObject, aTDShape, mySketchMgr->activeSketch());
809         if (anAttribute.first.get()) {
810           ModuleBase_WidgetFactory aFactory(theXmlRepr.toStdString(), workshop());
811
812           const std::string anAttributeId = anAttribute.first->id();
813           aFactory.createWidget(aPropertyPanel->contentWidget(), anAttributeId);
814
815           theWidgets = aFactory.getModelWidgets();
816           // it is possible that the point does not present in XML definition,
817           // in this case, we assume that it is not processed by this module
818           // e.g. "Intersection point" feature
819           aProcessed = !theWidgets.isEmpty();
820         }
821       }
822     }
823   }
824   return aProcessed;
825 }
826
827 //******************************************************
828 void PartSet_Module::onSelectionChanged()
829 {
830   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
831   if (!aOperation)
832     return;
833
834   bool isSketcherOp = false;
835   // An edit operation is enable only if the current opeation is the sketch operation
836   if (mySketchMgr->activeSketch()) {
837     if (PartSet_Tools::sketchPlane(mySketchMgr->activeSketch()))
838       isSketcherOp = PartSet_SketcherMgr::isSketchOperation(aOperation);
839   }
840   if (isSketcherOp) {
841     // Editing of constraints can be done on selection
842     ModuleBase_ISelection* aSelect = myWorkshop->selection();
843     QList<ModuleBase_ViewerPrsPtr> aSelected = aSelect->getSelected();
844     if (aSelected.size() == 1) {
845       ModuleBase_ViewerPrsPtr aPrs = aSelected.first();
846       ObjectPtr aObject = aPrs->object();
847       FeaturePtr aFeature = ModelAPI_Feature::feature(aObject);
848       if (aFeature) {
849         std::string aId = aFeature->getKind();
850         if ((aId == SketchPlugin_ConstraintRadius::ID()) ||
851             (aId == SketchPlugin_ConstraintLength::ID()) ||
852             (aId == SketchPlugin_ConstraintDistance::ID()) ||
853             (aId == SketchPlugin_ConstraintAngle::ID())) {
854           editFeature(aFeature);
855         }
856       }
857     }
858   }
859 }
860
861 //******************************************************
862 void PartSet_Module::onKeyRelease(ModuleBase_IViewWindow* theWnd, QKeyEvent* theEvent)
863 {
864   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
865   XGUI_OperationMgr* anOpMgr = aConnector->workshop()->operationMgr();
866   anOpMgr->onKeyReleased(theWnd->viewPort(), theEvent);
867 }
868
869 //******************************************************
870 ModuleBase_ModelWidget* PartSet_Module::createWidgetByType(const std::string& theType,
871                                                            QWidget* theParent,
872                                                            Config_WidgetAPI* theWidgetApi)
873 {
874   ModuleBase_IWorkshop* aWorkshop = workshop();
875   ModuleBase_ModelWidget* aWgt = NULL;
876   if (theType == "sketch-start-label") {
877     PartSet_WidgetSketchLabel* aLabelWgt = new PartSet_WidgetSketchLabel(theParent, aWorkshop,
878                                                                theWidgetApi, myHasConstraintShown);
879     connect(aLabelWgt, SIGNAL(planeSelected(const std::shared_ptr<GeomAPI_Pln>&)),
880       mySketchMgr, SLOT(onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>&)));
881     connect(aLabelWgt, SIGNAL(showConstraintToggled(int, bool)),
882       mySketchMgr, SLOT(onShowConstraintsToggle(int, bool)));
883     connect(aLabelWgt, SIGNAL(showFreePoints(bool)), mySketchMgr, SLOT(onShowPoints(bool)));
884     connect(aLabelWgt, SIGNAL(autoConstraints(bool)),
885       sketchReentranceMgr(), SLOT(onAutoConstraints(bool)));
886     aLabelWgt->setShowPointsState(mySketchMgr->isShowFreePointsShown());
887     aWgt = aLabelWgt;
888   } else if (theType == "sketch-2dpoint_selector") {
889     PartSet_WidgetPoint2D* aPointWgt = new PartSet_WidgetPoint2D(theParent, aWorkshop,
890                                                                  theWidgetApi);
891     aPointWgt->setSketch(mySketchMgr->activeSketch());
892     connect(aPointWgt, SIGNAL(vertexSelected()), sketchReentranceMgr(), SLOT(onVertexSelected()));
893     aWgt = aPointWgt;
894   }else if (theType == "sketch-2dpoint_flyout_selector") {
895     PartSet_WidgetPoint2DFlyout* aPointWgt = new PartSet_WidgetPoint2DFlyout(theParent, aWorkshop,
896                                                                              theWidgetApi);
897     aPointWgt->setSketch(mySketchMgr->activeSketch());
898     connect(aPointWgt, SIGNAL(vertexSelected()), sketchReentranceMgr(), SLOT(onVertexSelected()));
899     aWgt = aPointWgt;
900   } else if (theType == "sketch_shape_selector") {
901     PartSet_WidgetShapeSelector* aShapeSelectorWgt =
902                           new PartSet_WidgetShapeSelector(theParent, aWorkshop, theWidgetApi);
903     aShapeSelectorWgt->setSketcher(mySketchMgr->activeSketch());
904     aWgt = aShapeSelectorWgt;
905   } else if (theType == "sketch_multi_selector") {
906     PartSet_WidgetMultiSelector* aShapeSelectorWgt =
907                           new PartSet_WidgetMultiSelector(theParent, aWorkshop, theWidgetApi);
908     aShapeSelectorWgt->setSketcher(mySketchMgr->activeSketch());
909     aWgt = aShapeSelectorWgt;
910   }
911   else if (theType == "sketch_feature_point_selector") {
912     PartSet_WidgetFeaturePointSelector* aPointSelectorWgt =
913             new PartSet_WidgetFeaturePointSelector(theParent, aWorkshop, theWidgetApi);
914     aPointSelectorWgt->setSketcher(mySketchMgr->activeSketch());
915     aWgt = aPointSelectorWgt;
916   }
917   else if (theType == "sketch-bspline_selector") {
918     PartSet_WidgetBSplinePoints* aBSplineWgt =
919         new PartSet_WidgetBSplinePoints(theParent, aWorkshop, theWidgetApi);
920     aBSplineWgt->setSketch(mySketchMgr->activeSketch());
921     aWgt = aBSplineWgt;
922   }
923   else if (theType == WDG_DOUBLEVALUE_EDITOR) {
924     aWgt = new PartSet_WidgetEditor(theParent, aWorkshop, theWidgetApi);
925   } else if (theType == "export_file_selector") {
926     aWgt = new PartSet_WidgetFileSelector(theParent, aWorkshop, theWidgetApi);
927   } else if (theType == "sketch_launcher") {
928     aWgt = new PartSet_WidgetSketchCreator(theParent, this, theWidgetApi);
929   }
930   else if (theType == "module_choice") {
931     aWgt = new ModuleBase_WidgetChoice(theParent, theWidgetApi);
932     connect(aWgt, SIGNAL(itemSelected(ModuleBase_ModelWidget*, int)),
933       this, SLOT(onChoiceChanged(ModuleBase_ModelWidget*, int)));
934   } else if (theType == "bspline-panel") {
935     PartSet_BSplineWidget* aPanel = new PartSet_BSplineWidget(theParent, theWidgetApi);
936     //aPanel->setFeature(theFeature);
937     aWgt = aPanel;
938   }
939   return aWgt;
940 }
941
942 //******************************************************
943 ModuleBase_ModelWidget* PartSet_Module::activeWidget() const
944 {
945   ModuleBase_ModelWidget* anActiveWidget = 0;
946
947   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
948   if (!aOperation)
949     return anActiveWidget;
950
951   ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
952   if (!aPanel)
953     return anActiveWidget;
954
955   return aPanel->activeWidget(true);
956 }
957
958 //******************************************************
959 bool PartSet_Module::deleteObjects()
960 {
961   bool isProcessed = false;
962
963   XGUI_Workshop* aWorkshop = getWorkshop();
964   XGUI_OperationMgr* anOpMgr = aWorkshop->operationMgr();
965
966   //SessionPtr aMgr = ModelAPI_Session::get();
967   // 1. check whether the delete should be processed in the module
968   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
969   bool isSketchOp = PartSet_SketcherMgr::isSketchOperation(anOperation),
970        isNestedOp = sketchMgr()->isNestedSketchOperation(anOperation);
971   if (isSketchOp || isNestedOp) {
972     isProcessed = true;
973     // 2. find selected presentations
974     // selected objects should be collected before the current operation abort because
975     // the abort leads to selection lost on constraint objects. It can be corrected after #386 issue
976     ModuleBase_ISelection* aSel = workshop()->selection();
977     QObjectPtrList aSelectedObj = aSel->selectedPresentations();
978     // if there are no selected objects in the viewer, that means that the selection in another
979     // place cased this method. It is necessary to return the false value to understande in above
980     // method that delete is not processed
981     if (aSelectedObj.count() == 0)
982       return false;
983
984     // avoid delete of the objects, which are not belong to the current sketch
985     // in order to do not delete results of other sketches
986     QObjectPtrList aSketchObjects;
987     QObjectPtrList::const_iterator anIt = aSelectedObj.begin(), aLast = aSelectedObj.end();
988     for ( ; anIt != aLast; anIt++) {
989       ObjectPtr anObject = *anIt;
990       if (mySketchMgr->isObjectOfSketch(anObject)) {
991         // sketch feature should be used in this list because workshop deletes features only
992         // results are skipped
993         FeaturePtr aSketchFeature = ModelAPI_Feature::feature(anObject);
994         aSketchObjects.append(aSketchFeature);
995       }
996     }
997     // if the selection contains only local selected presentations from other sketches,
998     // the Delete operation should not be done at all
999     if (aSketchObjects.size() == 0)
1000       return true;
1001
1002     // 3. start operation
1003     QString aDescription = aWorkshop->contextMenuMgr()->action("DELETE_CMD")->text();
1004     ModuleBase_Operation* anOpAction = new ModuleBase_Operation(aDescription, this);
1005
1006     // the active nested sketch operation should be aborted unconditionally
1007     // the Delete action should be additionally granted for the Sketch operation
1008     // in order to do not abort/commit it
1009     bool isCommitted;
1010     if (!anOpMgr->canStartOperation(anOpAction->id(), isCommitted))
1011       return true; // the objects are processed but can not be deleted
1012
1013     anOpMgr->startOperation(anOpAction);
1014
1015     // WORKAROUND, should be done to avoid viewer highlight update after deletetion of objects
1016     // the problem is in AIS Dimensions recompute
1017     // if a line and the dim are removed, line is the first
1018     // it causes the AIS recompute, where the base line is null,
1019     // the result is empty AIS in the viewer
1020     XGUI_Tools::workshop(myWorkshop)->selector()->clearSelection();
1021
1022     // 4. delete features
1023     // sketch feature should be skipped, only sub-features can be removed
1024     // when sketch operation is active
1025     aWorkshop->deleteFeatures(aSketchObjects);
1026     // 5. stop operation
1027     anOpMgr->commitOperation();
1028   }
1029   return isProcessed;
1030 }
1031
1032 //******************************************************
1033 void PartSet_Module::editFeature(FeaturePtr theFeature)
1034 {
1035   storeConstraintsState(theFeature->getKind());
1036   ModuleBase_IModule::editFeature(theFeature);
1037 }
1038
1039 //******************************************************
1040 bool PartSet_Module::canCommitOperation() const
1041 {
1042   return true;
1043 }
1044
1045 //******************************************************
1046 void PartSet_Module::launchOperation(const QString& theCmdId, const bool& isStartAfterCommitOnly)
1047 {
1048   myIsOperationIsLaunched = true;
1049   storeConstraintsState(theCmdId.toStdString());
1050   updateConstraintsState(theCmdId.toStdString());
1051
1052   ModuleBase_IModule::launchOperation(theCmdId, isStartAfterCommitOnly);
1053
1054   myIsOperationIsLaunched = false;
1055 }
1056
1057 //******************************************************
1058 void PartSet_Module::storeConstraintsState(const std::string& theFeatureKind)
1059 {
1060   if (myWorkshop->currentOperation() &&
1061       myWorkshop->currentOperation()->id().toStdString() == SketchPlugin_Sketch::ID()) {
1062     const QMap<PartSet_Tools::ConstraintVisibleState, bool>& aShownStates =
1063                                                   mySketchMgr->showConstraintStates();
1064     myHasConstraintShown = aShownStates;
1065   }
1066 }
1067
1068 //******************************************************
1069 void PartSet_Module::updateConstraintsState(const std::string& theFeatureKind)
1070 {
1071   if (PartSet_SketcherMgr::constraintsIdList().contains(theFeatureKind.c_str()) ||
1072       PartSet_SketcherMgr::replicationsIdList().contains(theFeatureKind.c_str())) {
1073     // Show constraints if a constraint was anOperation
1074     mySketchMgr->updateBySketchParameters(PartSet_Tools::Geometrical, true);
1075     mySketchMgr->updateBySketchParameters(PartSet_Tools::Dimensional, true);
1076     mySketchMgr->updateBySketchParameters(PartSet_Tools::Expressions,
1077                                           myHasConstraintShown[PartSet_Tools::Expressions]);
1078   }
1079 }
1080
1081 //******************************************************
1082 void PartSet_Module::onObjectDisplayed(ObjectPtr theObject, AISObjectPtr theAIS)
1083 {
1084   Handle(AIS_InteractiveObject) anAIS = theAIS->impl<Handle(AIS_InteractiveObject)>();
1085   if (!anAIS.IsNull()) {
1086     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1087     if (aFeature.get()) {
1088       bool aToUseZLayer = false;
1089       if (PartSet_Tools::findRefsToMeFeature(aFeature,SketchPlugin_Projection::ID()))
1090         aToUseZLayer = true;
1091       else {
1092         CompositeFeaturePtr aParent = ModelAPI_Tools::compositeOwner(aFeature);
1093         aToUseZLayer = (aParent.get() && (aParent->getKind() == SketchPlugin_Sketch::ID()));
1094       }
1095       if (aToUseZLayer) {
1096         Handle(AIS_InteractiveContext) aCtx = anAIS->GetContext();
1097         if (aFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID())
1098           aCtx->SetZLayer(anAIS, Graphic3d_ZLayerId_Top);
1099         else
1100           aCtx->SetZLayer(anAIS, myVisualLayerId);
1101       }
1102     }
1103   }
1104 }
1105
1106 //******************************************************
1107 void PartSet_Module::onBeforeObjectErase(ObjectPtr theObject, AISObjectPtr theAIS)
1108 {
1109   // this is obsolete
1110   // it should be recomputed in order to disappear in the viewer if the corresponded object
1111   // is erased
1112   //if (myCustomPrs->isActive())
1113   //  myCustomPrs->redisplay(theObject, false);
1114 }
1115
1116 //******************************************************
1117 void PartSet_Module::onViewTransformed(int theTrsfType)
1118 {
1119   // Set length of arrows constant in pixel size
1120   // if the operation is panning or rotate or panglobal then do nothing
1121   if ((theTrsfType == 1) || (theTrsfType == 3) || (theTrsfType == 4))
1122     return;
1123   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
1124   Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
1125   if (aContext.IsNull())
1126     return;
1127
1128   //Handle(V3d_View) aView = aViewer->activeView();
1129
1130   XGUI_Workshop* aWorkshop = getWorkshop();
1131   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1132   Handle(V3d_Viewer) aV3dViewer = aContext->CurrentViewer();
1133   Handle(V3d_View) aView;
1134   double aScale = 0;
1135   for (aV3dViewer->InitDefinedViews();
1136        aV3dViewer->MoreDefinedViews();
1137        aV3dViewer->NextDefinedViews()) {
1138     Handle(V3d_View) aV = aV3dViewer->DefinedView();
1139     double aS = aV->Scale();
1140     if (aS > aScale) {
1141       aScale = aS;
1142       aView = aV;
1143     }
1144   }
1145   if (aView.IsNull())
1146     return;
1147
1148   bool isModified = false;
1149   ModuleBase_Operation* aCurrentOperation = myWorkshop->currentOperation();
1150   if (aCurrentOperation &&
1151     (PartSet_SketcherMgr::isSketchOperation(aCurrentOperation) ||
1152      sketchMgr()->isNestedSketchOperation(aCurrentOperation) ||
1153      (aCurrentOperation->id() == "Measurement")))
1154   {
1155     double aLen = aView->Convert(SketcherPrs_Tools::getConfigArrowSize());
1156     SketcherPrs_Tools::setArrowSize(aLen);
1157     const double aCurScale = aViewer->activeView()->Camera()->Scale();
1158     aViewer->SetScale(aViewer->activeView(), aCurScale);
1159 #ifdef OPTIMIZE_PRS
1160     QList<Handle(AIS_InteractiveObject)> aPrsList = aDisplayer->displayedPresentations();
1161     foreach(Handle(AIS_InteractiveObject) aAisObj, aPrsList) {
1162 #else
1163     QList<AISObjectPtr> aPrsList = aDisplayer->displayedPresentations();
1164     foreach(AISObjectPtr aAIS, aPrsList) {
1165       Handle(AIS_InteractiveObject) aAisObj = aAIS->impl<Handle(AIS_InteractiveObject)>();
1166 #endif
1167       Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(aAisObj);
1168       if (!aDim.IsNull()) {
1169         aDim->DimensionAspect()->ArrowAspect()->SetLength(aLen);
1170         aContext->Redisplay(aDim, false);
1171         isModified = true;
1172       }
1173     }
1174     if (isModified)
1175       aDisplayer->updateViewer();
1176   }
1177
1178 }
1179
1180 //******************************************************
1181 bool PartSet_Module::isCustomPrsActivated(const ModuleBase_CustomizeFlag& theFlag) const
1182 {
1183   return myCustomPrs->isActive(theFlag);
1184 }
1185
1186 //******************************************************
1187 void PartSet_Module::activateCustomPrs(const FeaturePtr& theFeature,
1188                                        const ModuleBase_CustomizeFlag& theFlag,
1189                                        const bool theUpdateViewer)
1190 {
1191   myCustomPrs->activate(theFeature, theFlag, theUpdateViewer);
1192 }
1193
1194 //******************************************************
1195 void PartSet_Module::deactivateCustomPrs(const ModuleBase_CustomizeFlag& theFlag,
1196                                          const bool theUpdateViewer)
1197 {
1198   myCustomPrs->deactivate(theFlag, theUpdateViewer);
1199 }
1200
1201 //******************************************************
1202 //bool PartSet_Module::customisePresentation(ResultPtr theResult, AISObjectPtr thePrs,
1203 //                                           std::shared_ptr<GeomAPI_ICustomPrs> theCustomPrs)
1204 //{
1205 //  bool aCustomized = false;
1206 //
1207 //  XGUI_Workshop* aWorkshop = getWorkshop();
1208 //  XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1209 //  ObjectPtr anObject = aDisplayer->getObject(thePrs);
1210 //  if (!anObject)
1211 //    return aCustomized;
1212 //
1213 //  if (!theResult.get()) {
1214 //    std::vector<int> aColor;
1215 //    XGUI_CustomPrs::getDefaultColor(anObject, true, aColor);
1216 //    if (!aColor.empty()) {
1217 //      aCustomized = thePrs->setColor(aColor[0], aColor[1], aColor[2]);
1218 //    }
1219 //  }
1220 //  // customize dimentional constrains
1221 //  sketchMgr()->customisePresentation(anObject);
1222 //
1223 //  return aCustomized;
1224 //}
1225 //
1226 ////******************************************************
1227 //bool PartSet_Module::afterCustomisePresentation(std::shared_ptr<ModelAPI_Result> theResult,
1228 //                                                AISObjectPtr thePrs,
1229 //                                                GeomCustomPrsPtr theCustomPrs)
1230 //{
1231 //  bool aCustomized = false;
1232 //
1233 //  XGUI_Workshop* aWorkshop = getWorkshop();
1234 //  XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1235 //  ObjectPtr anObject = aDisplayer->getObject(thePrs);
1236 //  if (!anObject)
1237 //    return aCustomized;
1238 //
1239 //  std::vector<int> aColor;
1240 //  bool aUseCustomColor = true;
1241 //  if (aUseCustomColor)
1242 //    myOverconstraintListener->getCustomColor(anObject, aColor);
1243 //  // customize sketch symbol presentation
1244 //  Handle(AIS_InteractiveObject) anAISIO = thePrs->impl<Handle(AIS_InteractiveObject)>();
1245 //  if (!anAISIO.IsNull()) {
1246 //    if (!Handle(SketcherPrs_SymbolPrs)::DownCast(anAISIO).IsNull()) {
1247 //      Handle(SketcherPrs_SymbolPrs) aPrs = Handle(SketcherPrs_SymbolPrs)::DownCast(anAISIO);
1248 //      if (!aPrs.IsNull()) {
1249 //        aPrs->SetCustomColor(aColor);
1250 //        aCustomized = true;
1251 //      }
1252 //    } else if (!Handle(SketcherPrs_Coincident)::DownCast(anAISIO).IsNull()) {
1253 //      Handle(SketcherPrs_Coincident) aPrs = Handle(SketcherPrs_Coincident)::DownCast(anAISIO);
1254 //      if (!aPrs.IsNull()) {
1255 //        aPrs->SetCustomColor(aColor);
1256 //        aCustomized = true;
1257 //      }
1258 //    }
1259 //  }
1260 //  // customize sketch dimension constraint presentation
1261 //  if (!aCustomized) {
1262 //    if (!aColor.empty()) { // otherwise presentation has the default color
1263 //      aCustomized = thePrs->setColor(aColor[0], aColor[1], aColor[2]);
1264 //    }
1265 //  }
1266 //  return aCustomized;
1267 //}
1268
1269 //******************************************************
1270 bool PartSet_Module::customizeFeature(ObjectPtr theObject, const ModuleBase_CustomizeFlag& theFlag,
1271                                      const bool theUpdateViewer)
1272 {
1273   bool isRedisplayed = false;
1274   if (myCustomPrs->isActive(theFlag))
1275     isRedisplayed = myCustomPrs->redisplay(theObject, theFlag, theUpdateViewer);
1276
1277   return isRedisplayed;
1278 }
1279
1280 //******************************************************
1281 void PartSet_Module::customizeObjectBrowser(QWidget* theObjectBrowser)
1282 {
1283   XGUI_ObjectsBrowser* aOB = dynamic_cast<XGUI_ObjectsBrowser*>(theObjectBrowser);
1284   if (aOB) {
1285     QLabel* aLabel = aOB->activeDocLabel();
1286     aLabel->installEventFilter(myMenuMgr);
1287     connect(aLabel, SIGNAL(customContextMenuRequested(const QPoint&)),
1288           SLOT(onActiveDocPopup(const QPoint&)));
1289     aOB->treeView()->setExpandsOnDoubleClick(false);
1290     connect(aOB->treeView(), SIGNAL(doubleClicked(const QModelIndex&)),
1291       SLOT(onTreeViewDoubleClick(const QModelIndex&)));
1292
1293     Events_Loop* aLoop = Events_Loop::loop();
1294     aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1295   }
1296 }
1297
1298 //******************************************************
1299 void PartSet_Module::onActiveDocPopup(const QPoint& thePnt)
1300 {
1301   SessionPtr aMgr = ModelAPI_Session::get();
1302   QAction* aActivatePartAction = myMenuMgr->action("ACTIVATE_PARTSET_CMD");
1303
1304   XGUI_Workshop* aWorkshop = getWorkshop();
1305   QLabel* aHeader = aWorkshop->objectBrowser()->activeDocLabel();
1306
1307   aActivatePartAction->setEnabled((aMgr->activeDocument() != aMgr->moduleDocument()));
1308
1309   QMenu aMenu;
1310   aMenu.addAction(aActivatePartAction);
1311
1312 #ifndef HAVE_SALOME
1313   if (aMgr->activeDocument() == aMgr->moduleDocument()) {
1314     DocumentPtr aDoc = aMgr->moduleDocument();
1315     int aNbParts = aDoc->size(ModelAPI_ResultPart::group());
1316     bool aHaveToActivate = false;
1317     for (int i = 0; i < aNbParts; i++) {
1318       ObjectPtr aObj = aDoc->object(ModelAPI_ResultPart::group(), i);
1319       ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1320       if (!aPartRes->partDoc().get()) {
1321         aHaveToActivate = true;
1322         break;
1323       }
1324     }
1325     if (aHaveToActivate) {
1326       QAction* aActivateAllPartAction = myMenuMgr->action("ACTIVATE_ALL_PARTS_CMD");
1327       aMenu.addAction(aActivateAllPartAction);
1328     }
1329   }
1330 #endif
1331
1332   aMenu.exec(aHeader->mapToGlobal(thePnt));
1333 }
1334
1335 //******************************************************
1336 AISObjectPtr PartSet_Module::createPresentation(const ObjectPtr& theObject)
1337 {
1338   Handle(AIS_InteractiveObject) anAISPrs = mySketchMgr->createPresentation(theObject);
1339   if (anAISPrs.IsNull()) {
1340     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1341     if (aResult.get()) {
1342       std::shared_ptr<GeomAPI_Shape> aShapePtr = ModelAPI_Tools::shape(aResult);
1343       if (aShapePtr.get() != NULL)
1344         anAISPrs = new ModuleBase_ResultPrs(aResult);
1345     }
1346     else {
1347       FieldStepPtr aStep =
1348         std::dynamic_pointer_cast<ModelAPI_ResultField::ModelAPI_FieldStep>(theObject);
1349       if (aStep.get()) {
1350         anAISPrs = new PartSet_FieldStepPrs(aStep);
1351       }
1352     }
1353   }
1354   AISObjectPtr anAIS;
1355   if (!anAISPrs.IsNull()) {
1356     Handle(AIS_Shape) aShapePrs = Handle(AIS_Shape)::DownCast(anAISPrs);
1357     if (!aShapePrs.IsNull())
1358       ModuleBase_Tools::setPointBallHighlighting((AIS_Shape*)aShapePrs.get());
1359
1360     anAIS = AISObjectPtr(new GeomAPI_AISObject());
1361     anAIS->setImpl(new Handle(AIS_InteractiveObject)(anAISPrs));
1362     customizePresentation(theObject, anAIS);
1363   }
1364   return anAIS;
1365 }
1366
1367 //******************************************************
1368 void getResultColor(const ResultPtr& theResult, std::vector<int>& theColor)
1369 {
1370   ModelAPI_Tools::getColor(theResult, theColor);
1371   if (theColor.empty())
1372     PartSet_Tools::getDefaultColor(theResult, false, theColor);
1373 }
1374
1375 //******************************************************
1376 double getResultDeflection(const ResultPtr& theResult)
1377 {
1378   double aDeflection = ModelAPI_Tools::getDeflection(theResult);
1379   if (aDeflection < 0)
1380     aDeflection = PartSet_Tools::getDefaultDeflection(theResult);
1381   return aDeflection;
1382 }
1383
1384 //******************************************************
1385 double getResultTransparency(const ResultPtr& theResult)
1386 {
1387   double aTransparency = ModelAPI_Tools::getTransparency(theResult);
1388   if (aTransparency < 0)
1389     aTransparency = PartSet_Tools::getDefaultTransparency();
1390   return aTransparency;
1391 }
1392
1393
1394 //******************************************************
1395 void PartSet_Module::customizePresentation(const ObjectPtr& theObject,
1396                                            const AISObjectPtr& thePrs) const
1397 {
1398   if (mySketchMgr->isObjectOfSketch(theObject)) {
1399     mySketchMgr->customizeSketchPresentation(theObject, thePrs);
1400   }
1401   else {
1402     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1403     if (aResult.get()) {
1404       std::vector<int> aColor;
1405       getResultColor(aResult, aColor);
1406
1407       SessionPtr aMgr = ModelAPI_Session::get();
1408       if (aMgr->activeDocument() != aResult->document()) {
1409         QColor aQColor(aColor[0], aColor[1], aColor[2]);
1410         QColor aNewColor =
1411           QColor::fromHsvF(aQColor.hueF(), aQColor.saturationF() / 3., aQColor.valueF());
1412         aColor[0] = aNewColor.red();
1413         aColor[1] = aNewColor.green();
1414         aColor[2] = aNewColor.blue();
1415       }
1416       thePrs->setColor(aColor[0], aColor[1], aColor[2]);
1417
1418       thePrs->setDeflection(getResultDeflection(aResult));
1419
1420       thePrs->setTransparency(getResultTransparency(aResult));
1421     }
1422     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1423     if (aFeature.get()) {
1424       if (aFeature->getKind() == SketchPlugin_Sketch::ID())
1425         thePrs->setWidth(2);
1426     }
1427   }
1428 }
1429
1430
1431 //******************************************************
1432 ObjectPtr PartSet_Module::findPresentedObject(const AISObjectPtr& theAIS) const
1433 {
1434   ObjectPtr anObject;
1435   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1436   if (aOperation) {
1437     /// If last line finished on vertex the lines creation sequence has to be break
1438     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
1439     if (aPanel) {
1440       ModuleBase_ModelWidget* anActiveWidget = aPanel->activeWidget();
1441       // if there is an active widget, find the presented object in it
1442       if (!anActiveWidget)
1443         anActiveWidget = aPanel->preselectionWidget();
1444
1445       ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
1446                                                                              (anActiveWidget);
1447       if (aWidgetValidated)
1448         anObject = aWidgetValidated->findPresentedObject(theAIS);
1449     }
1450   }
1451   return anObject;
1452 }
1453
1454 //******************************************************
1455 bool PartSet_Module::canBeShaded(Handle(AIS_InteractiveObject) theAIS) const
1456 {
1457   bool aCanBeShaged = true;
1458
1459   Handle(PartSet_ResultSketchPrs) aPrs = Handle(PartSet_ResultSketchPrs)::DownCast(theAIS);
1460   if (!aPrs.IsNull())
1461     aCanBeShaged = false;
1462
1463   return aCanBeShaged;
1464 }
1465
1466 //******************************************************
1467 void PartSet_Module::addObjectBrowserMenu(QMenu* theMenu) const
1468 {
1469   QObjectPtrList aObjects = myWorkshop->selection()->selectedObjects();
1470   int aSelected = aObjects.size();
1471   SessionPtr aMgr = ModelAPI_Session::get();
1472   QAction* aActivatePartAction = myMenuMgr->action("ACTIVATE_PART_CMD");
1473
1474   bool hasResult = false;
1475   bool hasFeature = false;
1476   bool hasParameter = false;
1477   bool hasCompositeOwner = false;
1478   bool hasResultInHistory = false;
1479   bool hasFolder = false;
1480   ModuleBase_Tools::checkObjects(aObjects, hasResult, hasFeature, hasParameter,
1481                                   hasCompositeOwner, hasResultInHistory, hasFolder);
1482
1483   ModuleBase_Operation* aCurrentOp = myWorkshop->currentOperation();
1484   if (aSelected == 1) {
1485     ObjectPtr aObject = aObjects.first();
1486     if (aObject) {
1487       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1488       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1489       bool isPart = aPart.get() ||
1490         (aFeature.get() && (aFeature->getKind() == PartSetPlugin_Part::ID()));
1491       if (isPart) {
1492         DocumentPtr aPartDoc;
1493         if (!aPart.get()) {
1494           aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFeature->firstResult());
1495         }
1496         if (aPart.get()) // this may be null is Part feature is disabled
1497           aPartDoc = aPart->partDoc();
1498
1499         theMenu->addAction(aActivatePartAction);
1500         aActivatePartAction->setEnabled((aMgr->activeDocument() != aPartDoc));
1501
1502       } else if (aObject->document() == aMgr->activeDocument()) {
1503         if (hasParameter || hasFeature) {
1504           myMenuMgr->action("EDIT_CMD")->setEnabled(true);
1505           theMenu->addAction(myMenuMgr->action("EDIT_CMD"));
1506           if (aCurrentOp && aFeature.get()) {
1507             if (aCurrentOp->id().toStdString() == aFeature->getKind())
1508               myMenuMgr->action("EDIT_CMD")->setEnabled(false);
1509           }
1510         }
1511       }
1512     }
1513   } else {
1514     if (hasFeature) {
1515       myMenuMgr->action("EDIT_CMD")->setEnabled(aCurrentOp == 0);
1516       theMenu->addAction(myMenuMgr->action("EDIT_CMD"));
1517       theMenu->addSeparator();
1518     }
1519   }
1520   bool aNotDeactivate = (aCurrentOp == 0);
1521   if (!aNotDeactivate) {
1522     aActivatePartAction->setEnabled(false);
1523   }
1524 }
1525
1526 //******************************************************
1527 #define EXPAND_PARENT(OBJ) \
1528 QModelIndex aObjIndex = aDataModel->objectIndex(OBJ); \
1529 if (aObjIndex.isValid()) { \
1530   QModelIndex aParent = aObjIndex.parent(); \
1531   int aCount = aDataModel->rowCount(aParent); \
1532   if (aCount == 1) \
1533     aTreeView->setExpanded(aParent, true); \
1534 }
1535
1536 //******************************************************
1537 void PartSet_Module::processEvent(const std::shared_ptr<Events_Message>& theMessage)
1538 {
1539   if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_DOCUMENT_CHANGED)) {
1540     SessionPtr aMgr = ModelAPI_Session::get();
1541     if (!aMgr->hasModuleDocument()) // if document is closed, do not call the document creation
1542       return;
1543     // Do not change activation of parts if an operation active
1544     static QStringList aAllowActivationList;
1545     if (aAllowActivationList.isEmpty())
1546       aAllowActivationList <<
1547       QString(PartSetPlugin_Part::ID().c_str()) <<
1548       QString(PartSetPlugin_Duplicate::ID().c_str()) <<
1549       QString(PartSetPlugin_Remove::ID().c_str());
1550     if (myWorkshop->currentOperation() &&
1551       (!aAllowActivationList.contains(myWorkshop->currentOperation()->id())))
1552       return;
1553     XGUI_Workshop* aWorkshop = getWorkshop();
1554     bool needUpdate = false;
1555     XGUI_DataTree* aTreeView;
1556     if (aWorkshop->objectBrowser()) {
1557       aTreeView = aWorkshop->objectBrowser()->treeView();
1558       QLabel* aLabel = aWorkshop->objectBrowser()->activeDocLabel();
1559       QPalette aPalet = aLabel->palette();
1560
1561       DocumentPtr aActiveDoc = aMgr->activeDocument();
1562
1563       // Clear active part index if there is no Part documents
1564       // It could be not null if document was closed and opened a new
1565       // without closeDocument call
1566       if (aMgr->allOpenedDocuments().size() <= 1)
1567         myActivePartIndex = QModelIndex();
1568
1569       XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1570       QModelIndex aOldActive = myActivePartIndex;
1571       myActivePartIndex = aDataModel->documentRootIndex(aActiveDoc, 0);
1572       if (myActivePartIndex.isValid()) {
1573         needUpdate = aTreeView->isExpanded(myActivePartIndex);
1574         if (!needUpdate)
1575           aTreeView->setExpanded(myActivePartIndex, true);
1576       }
1577       if ((aOldActive != myActivePartIndex) && (aOldActive.isValid()))
1578         aTreeView->setExpanded(aOldActive, false);
1579
1580       aLabel->setPalette(aPalet);
1581     }
1582     aWorkshop->updateCommandStatus();
1583
1584     // Update displayed objects in order to update active color
1585     XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1586     QObjectPtrList aObjects = aDisplayer->displayedObjects();
1587     bool aHidden;
1588     foreach(ObjectPtr aObj, aObjects) {
1589       aHidden = !aObj->data() || !aObj->data()->isValid() ||
1590         aObj->isDisabled() || (!aObj->isDisplayed());
1591       if (!aHidden) {
1592         aDisplayer->redisplay(aObj, false);
1593       }
1594     }
1595     aDisplayer->updateViewer();
1596     // Update tree items if they are expanded
1597     if (needUpdate) {
1598       aTreeView->viewport()->update(aTreeView->viewport()->rect());
1599     }
1600   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
1601     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
1602         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
1603     std::set<ObjectPtr> aObjects = aUpdMsg->objects();
1604
1605     ObjectPtr aConstrObj;
1606     ObjectPtr aResultObj;
1607     std::set<ObjectPtr>::const_iterator aIt;
1608     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
1609     for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
1610       ObjectPtr aObject = (*aIt);
1611       if ((!aResultObj.get()) && (aObject->groupName() == ModelAPI_ResultBody::group())
1612           && (aObject->document() != aRootDoc))
1613         aResultObj = aObject;
1614       if ((!aConstrObj.get()) && (aObject->groupName() == ModelAPI_ResultConstruction::group())
1615           && (aObject->document() != aRootDoc))
1616         aConstrObj = aObject;
1617       if (aResultObj.get() && aConstrObj.get())
1618         break;
1619     }
1620
1621     if (aResultObj.get() || aConstrObj.get()) {
1622       XGUI_Workshop* aWorkshop = getWorkshop();
1623       XGUI_DataTree* aTreeView = aWorkshop->objectBrowser()->treeView();
1624       XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1625
1626       if (aResultObj.get()) {
1627         EXPAND_PARENT(aResultObj)
1628       }
1629       if (aConstrObj.get()) {
1630         EXPAND_PARENT(aConstrObj)
1631       }
1632     }
1633   }
1634   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY)) {
1635     CompositeFeaturePtr aSketch = mySketchMgr->activeSketch();
1636     if (aSketch.get()) {
1637       ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
1638       if (PartSet_SketcherMgr::isSketchOperation(anOperation))
1639         mySketchMgr->previewSketchPlane()->createSketchPlane(aSketch, myWorkshop);
1640     }
1641   }
1642 }
1643
1644 //******************************************************
1645 void PartSet_Module::onTreeViewDoubleClick(const QModelIndex& theIndex)
1646 {
1647   if (myWorkshop->currentOperation()) // Do not change activation of parts if an operation active
1648     return;
1649   SessionPtr aMgr = ModelAPI_Session::get();
1650   if (!theIndex.isValid()) {
1651     // It seems that this code is obsolete
1652     //aMgr->setActiveDocument(aMgr->moduleDocument());
1653     return;
1654   }
1655   if (theIndex.column() != 1) // Use only first column
1656     return;
1657
1658   XGUI_Workshop* aWorkshop = getWorkshop();
1659   XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1660   // De not use non editable Indexes
1661   if ((aDataModel->flags(theIndex) & Qt::ItemIsSelectable) == 0)
1662     return;
1663   ObjectPtr aObj = aDataModel->object(theIndex);
1664
1665   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1666   if (!aPart.get()) { // Probably this is Feature
1667     FeaturePtr aPartFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
1668     if (aPartFeature.get() && (aPartFeature->getKind() == PartSetPlugin_Part::ID())) {
1669       aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aPartFeature->firstResult());
1670     }
1671   }
1672   if (aPart.get()) { // if this is a part
1673     if (aPart->partDoc() == aMgr->activeDocument()) {
1674       myMenuMgr->activatePartSet();
1675     } else {
1676       myMenuMgr->activatePart(aPart);
1677     }
1678   }
1679 }
1680
1681 //******************************************************
1682 void PartSet_Module::onViewCreated(ModuleBase_IViewWindow*)
1683 {
1684   // z layer is created for all started operations in order to visualize operation AIS presentation
1685   // over the object
1686   Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
1687   if (aContext.IsNull())
1688     return;
1689
1690   Handle(V3d_Viewer) aViewer = aContext->CurrentViewer();
1691   if (myVisualLayerId == 0) {
1692     if (myVisualLayerId == 0)
1693       aViewer->AddZLayer(myVisualLayerId);
1694   } else {
1695     TColStd_SequenceOfInteger aZList;
1696     aViewer->GetAllZLayers(aZList);
1697     bool aFound = false;
1698     for (int i = 1; i <= aZList.Length(); i++) {
1699       if (aZList(i) == myVisualLayerId) {
1700         aFound = true;
1701         break;
1702       }
1703     }
1704     if (!aFound)
1705       aViewer->AddZLayer(myVisualLayerId);
1706   }
1707   // if there is an active operation with validated widget,
1708   // the filters of this widget should be activated in the created view
1709   myWorkshop->selectionActivate()->updateSelectionFilters();
1710   myWorkshop->selectionActivate()->updateSelectionModes();
1711 }
1712
1713 //******************************************************
1714 void PartSet_Module::widgetStateChanged(int thePreviousState)
1715 {
1716   mySketchMgr->widgetStateChanged(thePreviousState);
1717 }
1718
1719 //******************************************************
1720 bool PartSet_Module::processEnter(const std::string& thePreviousAttributeID)
1721 {
1722   return mySketchReentrantMgr->processEnter(thePreviousAttributeID);
1723 }
1724
1725 //******************************************************
1726 void PartSet_Module::beforeOperationStopped(ModuleBase_Operation* theOperation)
1727 {
1728   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
1729     mySketchMgr->stopSketch(theOperation);
1730   }
1731 }
1732
1733 //******************************************************
1734 GeomShapePtr PartSet_Module::findShape(const AttributePtr& theAttribute)
1735 {
1736   GeomShapePtr aGeomShape;
1737
1738   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
1739   if (anOperation && sketchMgr()->isNestedSketchOperation(anOperation)) {
1740     aGeomShape = PartSet_Tools::findShapeBy2DPoint(theAttribute, myWorkshop);
1741   }
1742   return aGeomShape;
1743 }
1744
1745 //******************************************************
1746 AttributePtr PartSet_Module::findAttribute(const ObjectPtr& theObject,
1747                                            const GeomShapePtr& theGeomShape)
1748 {
1749   AttributePtr anAttribute;
1750   GeomShapePtr aGeomShape = theGeomShape;
1751   if (!aGeomShape.get()) {
1752     // processing shape of result, e.g. sketch circle center is selected, this is a result
1753     // the geom shape is empty, the shape of result should be used
1754     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1755     if (aResult.get()) {
1756       aGeomShape = aResult->shape();
1757     }
1758   }
1759
1760   if (aGeomShape.get()) {
1761     TopoDS_Shape aTDSShape = aGeomShape->impl<TopoDS_Shape>();
1762     std::pair<AttributePtr, int> anAttrAndIndex =
1763         PartSet_Tools::findAttributeBy2dPoint(theObject, aTDSShape, mySketchMgr->activeSketch());
1764     return anAttrAndIndex.first;
1765   }
1766   return anAttribute;
1767 }
1768
1769 //******************************************************
1770 std::shared_ptr<Events_Message> PartSet_Module::reentrantMessage()
1771 {
1772   return sketchReentranceMgr()->reentrantMessage();
1773 }
1774
1775 //******************************************************
1776 void PartSet_Module::setReentrantPreSelection(const std::shared_ptr<Events_Message>& theMessage)
1777 {
1778   sketchReentranceMgr()->setReentrantPreSelection(theMessage);
1779 }
1780
1781 //******************************************************
1782 void PartSet_Module::onChoiceChanged(ModuleBase_ModelWidget* theWidget,
1783                                      int theIndex)
1784 {
1785   ModuleBase_WidgetChoice* aChoiceWidget = dynamic_cast<ModuleBase_WidgetChoice*>(theWidget);
1786   if (!aChoiceWidget)
1787     return;
1788
1789   QString aChoiceTitle = aChoiceWidget->getPropertyPanelTitle(theIndex);
1790   if (!aChoiceTitle.isEmpty()) {
1791     ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1792     if (!aOperation)
1793       return;
1794     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
1795     if (aPanel)
1796       aPanel->setWindowTitle(aChoiceTitle);
1797   }
1798 }
1799
1800 //******************************************************
1801 XGUI_Workshop* PartSet_Module::getWorkshop() const
1802 {
1803   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
1804   return aConnector->workshop();
1805 }
1806
1807 void PartSet_Module::setDefaultConstraintShown()
1808 {
1809   myHasConstraintShown[PartSet_Tools::Geometrical] = true;
1810   myHasConstraintShown[PartSet_Tools::Dimensional] = true;
1811   myHasConstraintShown[PartSet_Tools::Expressions] = false;
1812 }
1813
1814 //******************************************************
1815 ModuleBase_ITreeNode* PartSet_Module::rootNode() const
1816 {
1817   return myRoot;
1818 }
1819
1820 //******************************************************
1821 void PartSet_Module::disableCustomMode(ModuleBase_CustomizeFlag theMode) {
1822   myCustomPrs->disableCustomMode(theMode);
1823 }
1824
1825 //******************************************************
1826 void PartSet_Module::enableCustomModes() {
1827   myCustomPrs->enableCustomModes();
1828 }