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