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