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