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