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