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