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