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