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