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