Salome HOME
bos #20145: [CEA] Sketch's plane become visible again when unticking display of const...
[modules/shaper.git] / src / PartSet / PartSet_Module.cpp
1 // Copyright (C) 2014-2020  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include "PartSet_Module.h"
21 #include "PartSet_WidgetSketchLabel.h"
22 #include "PartSet_Validators.h"
23 #include "PartSet_Tools.h"
24 #include "PartSet_PreviewPlanes.h"
25 #include "PartSet_WidgetBSplinePoints.h"
26 #include "PartSet_WidgetPoint2d.h"
27 #include "PartSet_WidgetPoint2DFlyout.h"
28 #include "PartSet_WidgetShapeSelector.h"
29 #include "PartSet_WidgetMultiSelector.h"
30 #include "PartSet_WidgetFeaturePointSelector.h"
31 #include "PartSet_WidgetEditor.h"
32 #include "PartSet_WidgetFileSelector.h"
33 #include "PartSet_WidgetSketchCreator.h"
34 #include "PartSet_SketcherMgr.h"
35 #include "PartSet_SketcherReentrantMgr.h"
36 #include "PartSet_ResultSketchPrs.h"
37 #include "PartSet_MenuMgr.h"
38 #include "PartSet_CustomPrs.h"
39 #include "PartSet_IconFactory.h"
40 #include "PartSet_OverconstraintListener.h"
41 #include "PartSet_TreeNodes.h"
42 #include "PartSet_FieldStepPrs.h"
43 #include "PartSet_BSplineWidget.h"
44
45 #include "PartSet_Filters.h"
46 #include "PartSet_FilterInfinite.h"
47
48 #ifdef _DEBUG
49 #include <QDebug>
50 #endif
51
52 #include <PartSetPlugin_Remove.h>
53 #include <PartSetPlugin_Part.h>
54 #include <PartSetPlugin_Duplicate.h>
55
56 #include <SketchPlugin_ConstraintCoincidence.h>
57
58 #include <ModuleBase_Operation.h>
59 #include <ModuleBase_IViewer.h>
60 #include <ModuleBase_IViewWindow.h>
61 #include <ModuleBase_IPropertyPanel.h>
62 #include <ModuleBase_ISelectionActivate.h>
63 #include <ModuleBase_WidgetChoice.h>
64 #include <ModuleBase_WidgetEditor.h>
65 #include <ModuleBase_WidgetValidated.h>
66 #include <ModuleBase_Tools.h>
67 #include <ModuleBase_OperationFeature.h>
68 #include <ModuleBase_WidgetFactory.h>
69 #include <ModuleBase_OperationDescription.h>
70 #include <ModuleBase_ViewerPrs.h>
71 #include <ModuleBase_ResultPrs.h>
72
73 #include <ModelAPI_ResultField.h>
74 #include <ModelAPI_Object.h>
75 #include <ModelAPI_Events.h>
76 #include <ModelAPI_Validator.h>
77 #include <ModelAPI_Data.h>
78 #include <ModelAPI_Session.h>
79 #include <ModelAPI_ResultBody.h>
80 #include <ModelAPI_AttributeString.h>
81 #include <ModelAPI_AttributeSelectionList.h>
82 #include <ModelAPI_Tools.h>
83 #include <ModelAPI_ResultConstruction.h>
84 #include <ModelAPI_AttributeIntArray.h>
85 #include <ModelAPI_ResultGroup.h>
86
87 #include <GeomDataAPI_Point2D.h>
88 #include <GeomDataAPI_Point.h>
89 #include <GeomDataAPI_Dir.h>
90
91 #include <XGUI_ActiveControlMgr.h>
92 #include <XGUI_ActiveControlSelector.h>
93 #include <XGUI_ActionsMgr.h>
94 #include <XGUI_ContextMenuMgr.h>
95 #include <XGUI_DataModel.h>
96 #include <XGUI_Displayer.h>
97 #include <XGUI_ErrorMgr.h>
98 #include <XGUI_FacesPanelSelector.h>
99 #include <XGUI_ModuleConnector.h>
100 #include <XGUI_ObjectsBrowser.h>
101 #include <XGUI_OperationMgr.h>
102 #include <XGUI_PropertyPanel.h>
103 #include <XGUI_SelectionMgr.h>
104 #include <XGUI_Tools.h>
105 #include <XGUI_Workshop.h>
106
107 #include <SketchPlugin_ConstraintAngle.h>
108 #include <SketchPlugin_ConstraintLength.h>
109 #include <SketchPlugin_ConstraintDistance.h>
110 #include <SketchPlugin_ConstraintParallel.h>
111 #include <SketchPlugin_ConstraintPerpendicular.h>
112 #include <SketchPlugin_ConstraintRadius.h>
113 #include <SketchPlugin_Feature.h>
114 #include <SketchPlugin_Projection.h>
115 #include <SketchPlugin_Sketch.h>
116
117 #include <SketcherPrs_SymbolPrs.h>
118 #include <SketcherPrs_PositionMgr.h>
119 #include <SketcherPrs_Coincident.h>
120 #include <SketcherPrs_Tools.h>
121
122 #include <Events_Loop.h>
123 #include <Config_PropManager.h>
124 #include <Config_Keywords.h>
125
126 #include <AIS_Dimension.hxx>
127 #include <AIS_InteractiveObject.hxx>
128 #include <StdSelect_TypeOfFace.hxx>
129 #include <TopoDS_Vertex.hxx>
130 #include <TopoDS.hxx>
131 #include <TopoDS_Shape.hxx>
132 #include <BRep_Tool.hxx>
133
134 #include <QObject>
135 #include <QMouseEvent>
136 #include <QString>
137 #include <QTimer>
138 #include <QApplication>
139 #include <QMessageBox>
140 #include <QMainWindow>
141 #include <QLineEdit>
142 #include <QString>
143
144 #include <GeomAlgoAPI_FaceBuilder.h>
145 #include <GeomDataAPI_Dir.h>
146
147 #include <SelectMgr_ListIteratorOfListOfFilter.hxx>
148
149 #define FEATURE_ITEM_COLOR "0,0,225"
150
151
152 /*!Create and return new instance of XGUI_Module*/
153 extern "C" PARTSET_EXPORT ModuleBase_IModule* createModule(ModuleBase_IWorkshop* theWshop)
154 {
155   return new PartSet_Module(theWshop);
156 }
157
158 //******************************************************
159 PartSet_Module::PartSet_Module(ModuleBase_IWorkshop* theWshop)
160 : ModuleBase_IModule(theWshop),
161   myIsOperationIsLaunched(false),
162   myVisualLayerId(0),
163   myRoot(0)
164 {
165   new PartSet_IconFactory(this);
166
167   mySketchMgr = new PartSet_SketcherMgr(this);
168   mySketchReentrantMgr = new PartSet_SketcherReentrantMgr(theWshop);
169
170   ModuleBase_IViewer* aViewer = theWshop->viewer();
171   connect(aViewer, SIGNAL(keyRelease(ModuleBase_IViewWindow*, QKeyEvent*)),
172           this, SLOT(onKeyRelease(ModuleBase_IViewWindow*, QKeyEvent*)));
173   connect(aViewer, SIGNAL(viewTransformed(int)),
174           SLOT(onViewTransformed(int)));
175   connect(aViewer, SIGNAL(viewCreated(ModuleBase_IViewWindow*)),
176           SLOT(onViewCreated(ModuleBase_IViewWindow*)));
177   myMenuMgr = new PartSet_MenuMgr(this);
178   myCustomPrs = new PartSet_CustomPrs(theWshop);
179
180   myOverconstraintListener = new PartSet_OverconstraintListener(theWshop);
181
182   Events_Loop* aLoop = Events_Loop::loop();
183   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_DOCUMENT_CHANGED));
184   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
185
186   registerSelectionFilter(SF_GlobalFilter, new PartSet_GlobalFilter(myWorkshop));
187   registerSelectionFilter(SF_FilterInfinite, new PartSet_FilterInfinite(myWorkshop));
188   Handle(PartSet_ResultGroupNameFilter) aCRFilter = new PartSet_ResultGroupNameFilter(myWorkshop);
189   std::set<std::string> aCRGroupNames;
190   aCRGroupNames.insert(ModelAPI_ResultConstruction::group());
191   aCRFilter->setGroupNames(aCRGroupNames);
192   registerSelectionFilter(SF_ResultGroupNameFilter, aCRFilter);
193
194   setDefaultConstraintShown();
195
196   //Config_PropManager::registerProp("Visualization", "object_default_color", "Object color",
197   //                                 Config_Prop::Color, "225,225,225");
198
199   Config_PropManager::registerProp("Visualization", "result_body_color", "Result color",
200     Config_Prop::Color, ModelAPI_ResultBody::DEFAULT_COLOR());
201
202   Config_PropManager::registerProp("Visualization", "result_group_color", "Group color",
203     Config_Prop::Color, ModelAPI_ResultGroup::DEFAULT_COLOR());
204
205   Config_PropManager::registerProp("Visualization", "result_construction_color",
206     "Construction color",
207     Config_Prop::Color,
208     ModelAPI_ResultConstruction::DEFAULT_COLOR());
209
210   Config_PropManager::registerProp("Visualization", "result_part_color", "Part color",
211     Config_Prop::Color, ModelAPI_ResultPart::DEFAULT_COLOR());
212
213   Config_PropManager::registerProp("Visualization", "result_field_color", "Field color",
214     Config_Prop::Color, ModelAPI_ResultField::DEFAULT_COLOR());
215
216   Config_PropManager::registerProp("Visualization", "operation_parameter_color",
217                           "Reference shape wireframe color in operation", Config_Prop::Color,
218                           PartSet_CustomPrs::OPERATION_PARAMETER_COLOR());
219   Config_PropManager::registerProp("Visualization", "operation_result_color",
220                           "Result shape wireframe color in operation", Config_Prop::Color,
221                           PartSet_CustomPrs::OPERATION_RESULT_COLOR());
222   Config_PropManager::registerProp("Visualization", "operation_highlight_color",
223                           "Multi selector item color in operation", Config_Prop::Color,
224                           PartSet_CustomPrs::OPERATION_HIGHLIGHT_COLOR());
225   Config_PropManager::registerProp("Visualization", "operation_remove_feature_color",
226                           "Color of removed feature in operation", Config_Prop::Color,
227                           PartSet_CustomPrs::OPERATION_REMOVE_FEATURE_COLOR());
228   Config_PropManager::registerProp("Visualization", "sketch_preview_plane",
229                           "Color of sketch plane", Config_Prop::Color,
230                           PartSet_CustomPrs::OPERATION_SKETCH_PLANE());
231
232   Config_PropManager::registerProp("Visualization", "hidden_face_transparency",
233                                    "Hidden faces transparency",
234                                    Config_Prop::DblSpin,
235                                    "0.8");
236
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 void getResultColor(const ResultPtr& theResult, std::vector<int>& theColor)
1390 {
1391   ModelAPI_Tools::getColor(theResult, theColor);
1392   if (theColor.empty())
1393     PartSet_Tools::getDefaultColor(theResult, false, theColor);
1394 }
1395
1396 //******************************************************
1397 double getResultDeflection(const ResultPtr& theResult)
1398 {
1399   double aDeflection = ModelAPI_Tools::getDeflection(theResult);
1400   if (aDeflection < 0)
1401     aDeflection = PartSet_Tools::getDefaultDeflection(theResult);
1402   return aDeflection;
1403 }
1404
1405 //******************************************************
1406 double getResultTransparency(const ResultPtr& theResult)
1407 {
1408   double aTransparency = ModelAPI_Tools::getTransparency(theResult);
1409   if (aTransparency < 0)
1410     aTransparency = PartSet_Tools::getDefaultTransparency();
1411   return aTransparency;
1412 }
1413
1414
1415 //******************************************************
1416 void PartSet_Module::customizePresentation(const ObjectPtr& theObject,
1417                                            const AISObjectPtr& thePrs) const
1418 {
1419   if (mySketchMgr->isObjectOfSketch(theObject)) {
1420     mySketchMgr->customizeSketchPresentation(theObject, thePrs);
1421   }
1422   else {
1423     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1424     if (aResult.get()) {
1425       std::vector<int> aColor;
1426       getResultColor(aResult, aColor);
1427
1428       SessionPtr aMgr = ModelAPI_Session::get();
1429       if (aMgr->activeDocument() != aResult->document()) {
1430         QColor aQColor(aColor[0], aColor[1], aColor[2]);
1431         QColor aNewColor =
1432           QColor::fromHsvF(aQColor.hueF(), aQColor.saturationF() / 3., aQColor.valueF());
1433         aColor[0] = aNewColor.red();
1434         aColor[1] = aNewColor.green();
1435         aColor[2] = aNewColor.blue();
1436       }
1437       thePrs->setColor(aColor[0], aColor[1], aColor[2]);
1438
1439       thePrs->setDeflection(getResultDeflection(aResult));
1440
1441       thePrs->setTransparency(getResultTransparency(aResult));
1442     }
1443     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1444     if (aFeature.get()) {
1445       if (aFeature->getKind() == SketchPlugin_Sketch::ID())
1446         thePrs->setWidth(2);
1447     }
1448   }
1449 }
1450
1451
1452 //******************************************************
1453 ObjectPtr PartSet_Module::findPresentedObject(const AISObjectPtr& theAIS) const
1454 {
1455   ObjectPtr anObject;
1456   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1457   if (aOperation) {
1458     /// If last line finished on vertex the lines creation sequence has to be break
1459     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
1460     if (aPanel) {
1461       ModuleBase_ModelWidget* anActiveWidget = aPanel->activeWidget();
1462       // if there is an active widget, find the presented object in it
1463       if (!anActiveWidget)
1464         anActiveWidget = aPanel->preselectionWidget();
1465
1466       ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
1467                                                                              (anActiveWidget);
1468       if (aWidgetValidated)
1469         anObject = aWidgetValidated->findPresentedObject(theAIS);
1470     }
1471   }
1472   return anObject;
1473 }
1474
1475 //******************************************************
1476 bool PartSet_Module::canBeShaded(Handle(AIS_InteractiveObject) theAIS) const
1477 {
1478   bool aCanBeShaged = true;
1479
1480   Handle(PartSet_ResultSketchPrs) aPrs = Handle(PartSet_ResultSketchPrs)::DownCast(theAIS);
1481   if (!aPrs.IsNull())
1482     aCanBeShaged = false;
1483
1484   return aCanBeShaged;
1485 }
1486
1487 //******************************************************
1488 void PartSet_Module::addObjectBrowserMenu(QMenu* theMenu) const
1489 {
1490   QObjectPtrList aObjects = myWorkshop->selection()->selectedObjects();
1491   int aSelected = aObjects.size();
1492   SessionPtr aMgr = ModelAPI_Session::get();
1493   QAction* aActivatePartAction = myMenuMgr->action("ACTIVATE_PART_CMD");
1494
1495   bool hasResult = false;
1496   bool hasFeature = false;
1497   bool hasParameter = false;
1498   bool hasCompositeOwner = false;
1499   bool hasResultInHistory = false;
1500   bool hasFolder = false;
1501   ModuleBase_Tools::checkObjects(aObjects, hasResult, hasFeature, hasParameter,
1502                                   hasCompositeOwner, hasResultInHistory, hasFolder);
1503
1504   ModuleBase_Operation* aCurrentOp = myWorkshop->currentOperation();
1505   if (aSelected == 1) {
1506     ObjectPtr aObject = aObjects.first();
1507     if (aObject) {
1508       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1509       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1510       bool isPart = aPart.get() ||
1511         (aFeature.get() && (aFeature->getKind() == PartSetPlugin_Part::ID()));
1512       if (isPart) {
1513         DocumentPtr aPartDoc;
1514         if (!aPart.get()) {
1515           aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFeature->firstResult());
1516         }
1517         if (aPart.get()) // this may be null is Part feature is disabled
1518           aPartDoc = aPart->partDoc();
1519
1520         theMenu->addAction(aActivatePartAction);
1521         aActivatePartAction->setEnabled((aMgr->activeDocument() != aPartDoc));
1522
1523       } else if (aObject->document() == aMgr->activeDocument()) {
1524         if (hasParameter || hasFeature) {
1525           myMenuMgr->action("EDIT_CMD")->setEnabled(true);
1526           theMenu->addAction(myMenuMgr->action("EDIT_CMD"));
1527           if (aCurrentOp && aFeature.get()) {
1528             if (aCurrentOp->id().toStdString() == aFeature->getKind())
1529               myMenuMgr->action("EDIT_CMD")->setEnabled(false);
1530           }
1531         }
1532       }
1533     }
1534   } else {
1535     if (hasFeature) {
1536       myMenuMgr->action("EDIT_CMD")->setEnabled(aCurrentOp == 0);
1537       theMenu->addAction(myMenuMgr->action("EDIT_CMD"));
1538       theMenu->addSeparator();
1539     }
1540   }
1541   bool aNotDeactivate = (aCurrentOp == 0);
1542   if (!aNotDeactivate) {
1543     aActivatePartAction->setEnabled(false);
1544   }
1545 }
1546
1547 //******************************************************
1548 #define EXPAND_PARENT(OBJ) \
1549 QModelIndex aObjIndex = aDataModel->objectIndex(OBJ); \
1550 if (aObjIndex.isValid()) { \
1551   QModelIndex aParent = aObjIndex.parent(); \
1552   int aCount = aDataModel->rowCount(aParent); \
1553   if (aCount == 1) \
1554     aTreeView->setExpanded(aParent, true); \
1555 }
1556
1557 //******************************************************
1558 void PartSet_Module::processEvent(const std::shared_ptr<Events_Message>& theMessage)
1559 {
1560   if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_DOCUMENT_CHANGED)) {
1561     SessionPtr aMgr = ModelAPI_Session::get();
1562     if (!aMgr->hasModuleDocument()) // if document is closed, do not call the document creation
1563       return;
1564     // Do not change activation of parts if an operation active
1565     static QStringList aAllowActivationList;
1566     if (aAllowActivationList.isEmpty())
1567       aAllowActivationList <<
1568       QString(PartSetPlugin_Part::ID().c_str()) <<
1569       QString(PartSetPlugin_Duplicate::ID().c_str()) <<
1570       QString(PartSetPlugin_Remove::ID().c_str());
1571     if (myWorkshop->currentOperation() &&
1572       (!aAllowActivationList.contains(myWorkshop->currentOperation()->id())))
1573       return;
1574     XGUI_Workshop* aWorkshop = getWorkshop();
1575     bool needUpdate = false;
1576     XGUI_DataTree* aTreeView = 0;
1577     if (aWorkshop->objectBrowser()) {
1578       aTreeView = aWorkshop->objectBrowser()->treeView();
1579       QLabel* aLabel = aWorkshop->objectBrowser()->activeDocLabel();
1580       QPalette aPalet = aLabel->palette();
1581
1582       DocumentPtr aActiveDoc = aMgr->activeDocument();
1583
1584       // Clear active part index if there is no Part documents
1585       // It could be not null if document was closed and opened a new
1586       // without closeDocument call
1587       if (aMgr->allOpenedDocuments().size() <= 1)
1588         myActivePartIndex = QModelIndex();
1589
1590       XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1591       QModelIndex aOldActive = myActivePartIndex;
1592       myActivePartIndex = aDataModel->documentRootIndex(aActiveDoc, 0);
1593       if (myActivePartIndex.isValid()) {
1594         needUpdate = aTreeView->isExpanded(myActivePartIndex);
1595         if (!needUpdate)
1596           aTreeView->setExpanded(myActivePartIndex, true);
1597       }
1598       if ((aOldActive != myActivePartIndex) && (aOldActive.isValid()))
1599         aTreeView->setExpanded(aOldActive, false);
1600
1601       aLabel->setPalette(aPalet);
1602     }
1603     aWorkshop->updateCommandStatus();
1604
1605     // Update displayed objects in order to update active color
1606     XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1607     QObjectPtrList aObjects = aDisplayer->displayedObjects();
1608     bool aHidden;
1609     foreach(ObjectPtr aObj, aObjects) {
1610       aHidden = !aObj->data() || !aObj->data()->isValid() ||
1611         aObj->isDisabled() || (!aObj->isDisplayed());
1612       if (!aHidden) {
1613         aDisplayer->redisplay(aObj, false);
1614       }
1615     }
1616     aDisplayer->updateViewer();
1617     // Update tree items if they are expanded
1618     if (needUpdate) {
1619       aTreeView->viewport()->update(aTreeView->viewport()->rect());
1620     }
1621   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
1622     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
1623         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
1624     std::set<ObjectPtr> aObjects = aUpdMsg->objects();
1625
1626     ObjectPtr aConstrObj;
1627     ObjectPtr aResultObj;
1628     std::set<ObjectPtr>::const_iterator aIt;
1629     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
1630     for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
1631       ObjectPtr aObject = (*aIt);
1632       if ((!aResultObj.get()) && (aObject->groupName() == ModelAPI_ResultBody::group())
1633           && (aObject->document() != aRootDoc))
1634         aResultObj = aObject;
1635       if ((!aConstrObj.get()) && (aObject->groupName() == ModelAPI_ResultConstruction::group())
1636           && (aObject->document() != aRootDoc))
1637         aConstrObj = aObject;
1638       if (aResultObj.get() && aConstrObj.get())
1639         break;
1640     }
1641
1642     if (aResultObj.get() || aConstrObj.get()) {
1643       XGUI_Workshop* aWorkshop = getWorkshop();
1644       XGUI_DataTree* aTreeView = aWorkshop->objectBrowser()->treeView();
1645       XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1646
1647       if (aResultObj.get()) {
1648         EXPAND_PARENT(aResultObj)
1649       }
1650       if (aConstrObj.get()) {
1651         EXPAND_PARENT(aConstrObj)
1652       }
1653     }
1654   }
1655   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY)) {
1656     CompositeFeaturePtr aSketch = mySketchMgr->activeSketch();
1657     if (aSketch.get()) {
1658       ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
1659       if (PartSet_SketcherMgr::isSketchOperation(anOperation) && mySketchMgr->previewSketchPlane()->isDisplayed())
1660         mySketchMgr->previewSketchPlane()->createSketchPlane(aSketch, myWorkshop);
1661     }
1662   }
1663 }
1664
1665 //******************************************************
1666 void PartSet_Module::onTreeViewDoubleClick(const QModelIndex& theIndex)
1667 {
1668   if (myWorkshop->currentOperation()) // Do not change activation of parts if an operation active
1669     return;
1670   SessionPtr aMgr = ModelAPI_Session::get();
1671   if (!theIndex.isValid()) {
1672     // It seems that this code is obsolete
1673     //aMgr->setActiveDocument(aMgr->moduleDocument());
1674     return;
1675   }
1676   if (theIndex.column() != 1) // Use only first column
1677     return;
1678
1679   XGUI_Workshop* aWorkshop = getWorkshop();
1680   XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1681   // De not use non editable Indexes
1682   if ((aDataModel->flags(theIndex) & Qt::ItemIsSelectable) == 0)
1683     return;
1684   ObjectPtr aObj = aDataModel->object(theIndex);
1685
1686   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1687   if (!aPart.get()) { // Probably this is Feature
1688     FeaturePtr aPartFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
1689     if (aPartFeature.get() && (aPartFeature->getKind() == PartSetPlugin_Part::ID())) {
1690       aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aPartFeature->firstResult());
1691     }
1692   }
1693   if (aPart.get()) { // if this is a part
1694     if (aPart->partDoc() == aMgr->activeDocument()) {
1695       myMenuMgr->activatePartSet();
1696     } else {
1697       myMenuMgr->activatePart(aPart);
1698     }
1699   }
1700 }
1701
1702 //******************************************************
1703 void PartSet_Module::onViewCreated(ModuleBase_IViewWindow*)
1704 {
1705   // z layer is created for all started operations in order to visualize operation AIS presentation
1706   // over the object
1707   Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
1708   if (aContext.IsNull())
1709     return;
1710
1711   Handle(V3d_Viewer) aViewer = aContext->CurrentViewer();
1712   if (myVisualLayerId == 0) {
1713     if (myVisualLayerId == 0)
1714       aViewer->AddZLayer(myVisualLayerId);
1715   } else {
1716     TColStd_SequenceOfInteger aZList;
1717     aViewer->GetAllZLayers(aZList);
1718     bool aFound = false;
1719     for (int i = 1; i <= aZList.Length(); i++) {
1720       if (aZList(i) == myVisualLayerId) {
1721         aFound = true;
1722         break;
1723       }
1724     }
1725     if (!aFound)
1726       aViewer->AddZLayer(myVisualLayerId);
1727   }
1728   // if there is an active operation with validated widget,
1729   // the filters of this widget should be activated in the created view
1730   myWorkshop->selectionActivate()->updateSelectionFilters();
1731   myWorkshop->selectionActivate()->updateSelectionModes();
1732 }
1733
1734 //******************************************************
1735 void PartSet_Module::widgetStateChanged(int thePreviousState)
1736 {
1737   mySketchMgr->widgetStateChanged(thePreviousState);
1738 }
1739
1740 //******************************************************
1741 bool PartSet_Module::processEnter(const std::string& thePreviousAttributeID)
1742 {
1743   return mySketchReentrantMgr->processEnter(thePreviousAttributeID);
1744 }
1745
1746 //******************************************************
1747 void PartSet_Module::beforeOperationStopped(ModuleBase_Operation* theOperation)
1748 {
1749   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
1750     mySketchMgr->stopSketch(theOperation);
1751   }
1752 }
1753
1754 //******************************************************
1755 GeomShapePtr PartSet_Module::findShape(const AttributePtr& theAttribute)
1756 {
1757   GeomShapePtr aGeomShape;
1758
1759   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
1760   if (anOperation && sketchMgr()->isNestedSketchOperation(anOperation)) {
1761     aGeomShape = PartSet_Tools::findShapeBy2DPoint(theAttribute, myWorkshop);
1762   }
1763   return aGeomShape;
1764 }
1765
1766 //******************************************************
1767 AttributePtr PartSet_Module::findAttribute(const ObjectPtr& theObject,
1768                                            const GeomShapePtr& theGeomShape)
1769 {
1770   AttributePtr anAttribute;
1771   GeomShapePtr aGeomShape = theGeomShape;
1772   if (!aGeomShape.get()) {
1773     // processing shape of result, e.g. sketch circle center is selected, this is a result
1774     // the geom shape is empty, the shape of result should be used
1775     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1776     if (aResult.get()) {
1777       aGeomShape = aResult->shape();
1778     }
1779   }
1780
1781   if (aGeomShape.get()) {
1782     TopoDS_Shape aTDSShape = aGeomShape->impl<TopoDS_Shape>();
1783     std::pair<AttributePtr, int> anAttrAndIndex =
1784         PartSet_Tools::findAttributeBy2dPoint(theObject, aTDSShape, mySketchMgr->activeSketch());
1785     return anAttrAndIndex.first;
1786   }
1787   return anAttribute;
1788 }
1789
1790 //******************************************************
1791 std::shared_ptr<Events_Message> PartSet_Module::reentrantMessage()
1792 {
1793   return sketchReentranceMgr()->reentrantMessage();
1794 }
1795
1796 //******************************************************
1797 void PartSet_Module::setReentrantPreSelection(const std::shared_ptr<Events_Message>& theMessage)
1798 {
1799   sketchReentranceMgr()->setReentrantPreSelection(theMessage);
1800 }
1801
1802 //******************************************************
1803 void PartSet_Module::onChoiceChanged(ModuleBase_ModelWidget* theWidget,
1804                                      int theIndex)
1805 {
1806   ModuleBase_WidgetChoice* aChoiceWidget = dynamic_cast<ModuleBase_WidgetChoice*>(theWidget);
1807   if (!aChoiceWidget)
1808     return;
1809
1810   QString aChoiceTitle = aChoiceWidget->getPropertyPanelTitle(theIndex);
1811   if (!aChoiceTitle.isEmpty()) {
1812     ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1813     if (!aOperation)
1814       return;
1815     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
1816     if (aPanel)
1817       aPanel->setWindowTitle(aChoiceTitle);
1818   }
1819 }
1820
1821 //******************************************************
1822 XGUI_Workshop* PartSet_Module::getWorkshop() const
1823 {
1824   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
1825   return aConnector->workshop();
1826 }
1827
1828 void PartSet_Module::setDefaultConstraintShown()
1829 {
1830   myHasConstraintShown[PartSet_Tools::Geometrical] = true;
1831   myHasConstraintShown[PartSet_Tools::Dimensional] = true;
1832   myHasConstraintShown[PartSet_Tools::Expressions] = false;
1833 }
1834
1835 //******************************************************
1836 ModuleBase_ITreeNode* PartSet_Module::rootNode() const
1837 {
1838   return myRoot;
1839 }
1840
1841 //******************************************************
1842 void PartSet_Module::disableCustomMode(ModuleBase_CustomizeFlag theMode) {
1843   myCustomPrs->disableCustomMode(theMode);
1844 }
1845
1846 //******************************************************
1847 void PartSet_Module::enableCustomModes() {
1848   myCustomPrs->enableCustomModes();
1849 }
1850
1851 //******************************************************
1852 void PartSet_Module::onConflictingConstraints()
1853 {
1854   const std::set<ObjectPtr>& aConstraints = myOverconstraintListener->conflictingObjects();
1855   QObjectPtrList aObjectsList;
1856   std::set<ObjectPtr>::const_iterator aIt;
1857   for (aIt = aConstraints.cbegin(); aIt != aConstraints.cend(); aIt++) {
1858     if (mySketchReentrantMgr->isLastAutoConstraint(*aIt))
1859       aObjectsList.append(*aIt);
1860   }
1861   if (aObjectsList.size() > 0) {
1862     XGUI_Workshop* aWorkshop = getWorkshop();
1863     QString aDescription = aWorkshop->contextMenuMgr()->action("DELETE_CMD")->text();
1864     ModuleBase_Operation* anOpAction = new ModuleBase_Operation(aDescription);
1865     XGUI_OperationMgr* anOpMgr = aWorkshop->operationMgr();
1866
1867     ModuleBase_Operation* anOp = anOpMgr->currentOperation();
1868     if (sketchMgr()->isNestedSketchOperation(anOp))
1869       anOp->abort();
1870
1871     anOpMgr->startOperation(anOpAction);
1872     aWorkshop->deleteFeatures(aObjectsList);
1873     anOpMgr->commitOperation();
1874     ModuleBase_Tools::flushUpdated(sketchMgr()->activeSketch());
1875   }
1876 }