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