]> SALOME platform Git repositories - modules/shaper.git/blob - src/PartSet/PartSet_Module.cpp
Salome HOME
3947c7c3dd38a5a62d673a71ca1b5501ab99dff9
[modules/shaper.git] / src / PartSet / PartSet_Module.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 #include "PartSet_Module.h"
4 #include "PartSet_WidgetSketchLabel.h"
5 #include "PartSet_Validators.h"
6 #include "PartSet_Tools.h"
7 #include "PartSet_PreviewPlanes.h"
8 #include "PartSet_WidgetPoint2d.h"
9 #include "PartSet_WidgetPoint2dDistance.h"
10 #include "PartSet_WidgetPoint2DFlyout.h"
11 #include "PartSet_WidgetShapeSelector.h"
12 #include "PartSet_WidgetMultiSelector.h"
13 #include "PartSet_WidgetSubShapeSelector.h"
14 #include "PartSet_WidgetEditor.h"
15 #include "PartSet_WidgetFileSelector.h"
16 #include "PartSet_WidgetSketchCreator.h"
17 #include "PartSet_SketcherMgr.h"
18 #include "PartSet_SketcherReetntrantMgr.h"
19 #include "PartSet_ResultSketchPrs.h"
20 #include "PartSet_MenuMgr.h"
21 #include "PartSet_CustomPrs.h"
22 #include "PartSet_IconFactory.h"
23 #include "PartSet_WidgetChoice.h"
24 #include "PartSet_OverconstraintListener.h"
25
26 #include "PartSet_Filters.h"
27 #include "PartSet_FilterInfinite.h"
28
29 #include <PartSetPlugin_Remove.h>
30 #include <PartSetPlugin_Part.h>
31 #include <PartSetPlugin_Duplicate.h>
32
33 #include <ModuleBase_Operation.h>
34 #include <ModuleBase_OperationAction.h>
35 #include <ModuleBase_IViewer.h>
36 #include <ModuleBase_IViewWindow.h>
37 #include <ModuleBase_IPropertyPanel.h>
38 #include <ModuleBase_WidgetEditor.h>
39 #include <ModuleBase_WidgetValidated.h>
40 #include <ModuleBase_FilterFactory.h>
41 #include <ModuleBase_Tools.h>
42 #include <ModuleBase_OperationFeature.h>
43 #include <ModuleBase_WidgetFactory.h>
44 #include <ModuleBase_OperationDescription.h>
45 #include <ModuleBase_ViewerPrs.h>
46
47 #include <ModelAPI_Object.h>
48 #include <ModelAPI_Events.h>
49 #include <ModelAPI_Validator.h>
50 #include <ModelAPI_Data.h>
51 #include <ModelAPI_Session.h>
52 #include <ModelAPI_ResultBody.h>
53 #include <ModelAPI_AttributeString.h>
54 #include <ModelAPI_AttributeSelectionList.h>
55 #include <ModelAPI_Tools.h>
56 #include <ModelAPI_ResultConstruction.h>
57
58 #include <GeomDataAPI_Point2D.h>
59 #include <GeomDataAPI_Point.h>
60 #include <GeomDataAPI_Dir.h>
61
62 #include <XGUI_Displayer.h>
63 #include <XGUI_Workshop.h>
64 #include <XGUI_OperationMgr.h>
65 #include <XGUI_PropertyPanel.h>
66 #include <XGUI_ModuleConnector.h>
67 #include <XGUI_ContextMenuMgr.h>
68 #include <XGUI_Tools.h>
69 #include <XGUI_ObjectsBrowser.h>
70 #include <XGUI_SelectionMgr.h>
71 #include <XGUI_DataModel.h>
72 #include <XGUI_ErrorMgr.h>
73 #include <XGUI_CustomPrs.h>
74 #include <XGUI_SelectionMgr.h>
75 #include <XGUI_ActionsMgr.h>
76
77 #include <SketchPlugin_Feature.h>
78 #include <SketchPlugin_Sketch.h>
79 #include <SketchPlugin_ConstraintAngle.h>
80 #include <SketchPlugin_ConstraintLength.h>
81 #include <SketchPlugin_ConstraintDistance.h>
82 #include <SketchPlugin_ConstraintParallel.h>
83 #include <SketchPlugin_ConstraintPerpendicular.h>
84 #include <SketchPlugin_ConstraintRadius.h>
85
86 #include <SketcherPrs_SymbolPrs.h>
87 #include <SketcherPrs_Coincident.h>
88 #include <SketcherPrs_Tools.h>
89
90 #include <Events_Loop.h>
91 #include <Config_PropManager.h>
92 #include <Config_Keywords.h>
93
94 #include <AIS_Dimension.hxx>
95 #include <AIS_InteractiveObject.hxx>
96 #include <StdSelect_TypeOfFace.hxx>
97 #include <TopoDS_Vertex.hxx>
98 #include <TopoDS.hxx>
99 #include <TopoDS_Shape.hxx>
100 #include <BRep_Tool.hxx>
101
102 #include <QObject>
103 #include <QMouseEvent>
104 #include <QString>
105 #include <QTimer>
106 #include <QApplication>
107 #include <QMessageBox>
108 #include <QMainWindow>
109 #include <QLineEdit>
110 #include <QString>
111
112 #include <GeomAlgoAPI_FaceBuilder.h>
113 #include <GeomDataAPI_Dir.h>
114
115 #include <SelectMgr_ListIteratorOfListOfFilter.hxx>
116
117 #ifdef _DEBUG
118 #include <QDebug>
119 #endif
120
121 /*!Create and return new instance of XGUI_Module*/
122 extern "C" PARTSET_EXPORT ModuleBase_IModule* createModule(ModuleBase_IWorkshop* theWshop)
123 {
124   return new PartSet_Module(theWshop);
125 }
126
127 PartSet_Module::PartSet_Module(ModuleBase_IWorkshop* theWshop)
128 : ModuleBase_IModule(theWshop),
129   myVisualLayerId(0),
130   myIsOperationIsLaunched(false)
131 {
132   new PartSet_IconFactory();
133
134   mySketchMgr = new PartSet_SketcherMgr(this);
135   mySketchReentrantMgr = new PartSet_SketcherReetntrantMgr(theWshop);
136
137   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWshop);
138   XGUI_Workshop* aWorkshop = aConnector->workshop();
139
140   ModuleBase_IViewer* aViewer = theWshop->viewer();
141   connect(aViewer, SIGNAL(keyRelease(ModuleBase_IViewWindow*, QKeyEvent*)),
142           this, SLOT(onKeyRelease(ModuleBase_IViewWindow*, QKeyEvent*)));
143   connect(aViewer, SIGNAL(viewTransformed(int)),
144           SLOT(onViewTransformed(int)));
145   connect(aViewer, SIGNAL(viewCreated(ModuleBase_IViewWindow*)),
146           SLOT(onViewCreated(ModuleBase_IViewWindow*)));
147   myMenuMgr = new PartSet_MenuMgr(this);
148   myCustomPrs = new PartSet_CustomPrs(theWshop);
149
150   myOverconstraintListener = new PartSet_OverconstraintListener(theWshop);
151
152   Events_Loop* aLoop = Events_Loop::loop();
153   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_DOCUMENT_CHANGED));
154
155   mySelectionFilters.Append(new PartSet_GlobalFilter(myWorkshop));
156   mySelectionFilters.Append(new PartSet_FilterInfinite(myWorkshop));
157
158   setDefaultConstraintShown();
159
160   Config_PropManager::registerProp("Visualization", "operation_parameter_color",
161                           "Reference shape wireframe color in operation", Config_Prop::Color,
162                           PartSet_CustomPrs::OPERATION_PARAMETER_COLOR());
163   Config_PropManager::registerProp("Visualization", "operation_result_color",
164                           "Result shape wireframe color in operation", Config_Prop::Color,
165                           PartSet_CustomPrs::OPERATION_RESULT_COLOR());
166   Config_PropManager::registerProp("Visualization", "operation_highlight_color",
167                           "Multi selector item color in operation", Config_Prop::Color,
168                           PartSet_CustomPrs::OPERATION_HIGHLIGHT_COLOR());
169 }
170
171 PartSet_Module::~PartSet_Module()
172 {
173   SelectMgr_ListIteratorOfListOfFilter aIt(mySelectionFilters);
174   for (; aIt.More(); aIt.Next()) {
175     Handle(SelectMgr_Filter) aFilter = aIt.Value();
176     if (!aFilter.IsNull())
177       aFilter.Nullify();
178   }
179   delete myCustomPrs;
180   delete myOverconstraintListener;
181 }
182
183 void PartSet_Module::activateSelectionFilters()
184 {
185   SelectMgr_ListIteratorOfListOfFilter aIt(mySelectionFilters);
186   for (; aIt.More(); aIt.Next()) {
187     Handle(SelectMgr_Filter) aFilter = aIt.Value();
188     if (!aFilter.IsNull())
189       myWorkshop->viewer()->addSelectionFilter(aFilter);
190   }
191 }
192
193 void PartSet_Module::deactivateSelectionFilters()
194 {
195   SelectMgr_ListIteratorOfListOfFilter aIt(mySelectionFilters);
196   for (; aIt.More(); aIt.Next()) {
197     Handle(SelectMgr_Filter) aFilter = aIt.Value();
198     if (!aFilter.IsNull())
199       myWorkshop->viewer()->removeSelectionFilter(aFilter);
200   }
201 }
202
203 void PartSet_Module::storeSelection()
204 {
205   sketchMgr()->storeSelection();
206 }
207
208 void PartSet_Module::restoreSelection()
209 {
210   sketchMgr()->restoreSelection();
211 }
212
213 void PartSet_Module::registerValidators()
214 {
215   //Registering of validators
216   SessionPtr aMgr = ModelAPI_Session::get();
217   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
218   aFactory->registerValidator("PartSet_DistanceSelection", new PartSet_DistanceSelection);
219   aFactory->registerValidator("PartSet_LengthSelection", new PartSet_LengthSelection);
220   aFactory->registerValidator("PartSet_PerpendicularSelection", new PartSet_PerpendicularSelection);
221   aFactory->registerValidator("PartSet_ParallelSelection", new PartSet_ParallelSelection);
222   aFactory->registerValidator("PartSet_RadiusSelection", new PartSet_RadiusSelection);
223   aFactory->registerValidator("PartSet_RigidSelection", new PartSet_RigidSelection);
224   aFactory->registerValidator("PartSet_CoincidentSelection", new PartSet_CoincidentSelection);
225   aFactory->registerValidator("PartSet_HVDirSelection", new PartSet_HVDirSelection);
226   aFactory->registerValidator("PartSet_TangentSelection", new PartSet_TangentSelection);
227   aFactory->registerValidator("PartSet_FilletSelection", new PartSet_FilletSelection);
228   aFactory->registerValidator("PartSet_AngleSelection", new PartSet_AngleSelection);
229   aFactory->registerValidator("PartSet_EqualSelection", new PartSet_EqualSelection);
230   aFactory->registerValidator("PartSet_CollinearSelection", new PartSet_CollinearSelection);
231   aFactory->registerValidator("PartSet_MiddlePointSelection", new PartSet_MiddlePointSelection);
232   aFactory->registerValidator("PartSet_DifferentObjects", new PartSet_DifferentObjectsValidator);
233   aFactory->registerValidator("PartSet_CoincidentAttr", new PartSet_CoincidentAttr);
234   aFactory->registerValidator("PartSet_MultyTranslationSelection",
235     new PartSet_MultyTranslationSelection);
236   aFactory->registerValidator("PartSet_SplitSelection", new PartSet_SplitSelection);
237   aFactory->registerValidator("PartSet_ProjectionSelection", new PartSet_ProjectionSelection);
238 }
239
240 void PartSet_Module::registerFilters()
241 {
242   //Registering of selection filters
243   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
244   ModuleBase_FilterFactory* aFactory = aConnector->selectionFilters();
245 }
246
247 void PartSet_Module::registerProperties()
248 {
249   Config_PropManager::registerProp(SKETCH_TAB_NAME, "planes_size", "Size", Config_Prop::Double,
250                                    PLANE_SIZE);
251   Config_PropManager::registerProp(SKETCH_TAB_NAME, "planes_thickness", "Thickness",
252                                    Config_Prop::Integer, SKETCH_WIDTH);
253   Config_PropManager::registerProp(SKETCH_TAB_NAME, "rotate_to_plane",
254     "Rotate to plane when selected", Config_Prop::Boolean, "false");
255 }
256
257 void PartSet_Module::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget,
258                                             const bool isToConnect)
259 {
260   mySketchMgr->connectToPropertyPanel(theWidget, isToConnect);
261 }
262
263 void PartSet_Module::operationCommitted(ModuleBase_Operation* theOperation)
264 {
265   if (sketchMgr()->isNestedSketchOperation(theOperation)) {
266     mySketchMgr->commitNestedSketch(theOperation);
267   }
268
269   /// Restart sketcher operations automatically
270   if (!mySketchReentrantMgr->operationCommitted(theOperation)) {
271
272     ModuleBase_OperationFeature* aFOperation =
273       dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
274     if (aFOperation && !aFOperation->isEditOperation()) {
275       // the selection is cleared after commit the create operation
276       // in order to do not use the same selected objects in the restarted operation
277       // for common behaviour, the selection is cleared even if the operation is not restarted
278       getWorkshop()->selector()->clearSelection();
279     }
280   }
281 }
282
283 void PartSet_Module::operationAborted(ModuleBase_Operation* theOperation)
284 {
285   /// Restart sketcher operations automatically
286   mySketchReentrantMgr->operationAborted(theOperation);
287 }
288
289 void PartSet_Module::operationStarted(ModuleBase_Operation* theOperation)
290 {
291   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
292                                                                                 (theOperation);
293   if (aFOperation) {
294     XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(workshop());
295     XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
296
297     ModuleBase_ModelWidget* aFilledWidget = 0;
298     bool aPostonedWidgetActivation = false;
299
300     FeaturePtr aFeature = aFOperation->feature();
301     /// Restart sketcher operations automatically
302     /// it is important to call method of sketch reentrant manager before filling of PP
303     /// because it fills some created feature attributes, these new values should be used
304     /// to fill the property panel
305     mySketchReentrantMgr->operationStarted(theOperation);
306
307     aWorkshop->fillPropertyPanel(aFOperation);
308     // filling the operation values by the current selection
309     // if the operation can be committed after the controls filling, the method perform should
310     // be stopped. Otherwise unnecessary presentations can be shown(e.g. operation prs in sketch)
311     bool isOperationCommitted = false;
312     if (!aFOperation->isEditOperation()) {
313       std::string aGreedAttributeId = ModuleBase_Tools::findGreedAttribute(workshop(), aFeature);
314       // if there is a greed attribute, automatic commit by preselection
315       // for this feature is prohibited
316       aFilledWidget = aFOperation->activateByPreselection(aGreedAttributeId);
317       if (currentOperation() != aFOperation)
318         isOperationCommitted = true;
319       else {
320         if (aGreedAttributeId.empty()) {
321           // a signal should be emitted before the next widget activation
322           // because, the activation of the next widget will give a focus to the widget.
323           // As a result the value of the widget is initialized.
324           // And commit may happens until the value is entered.
325           if (aFilledWidget) {
326             if (mySketchReentrantMgr->canBeCommittedByPreselection())
327               isOperationCommitted = mySketchMgr->operationActivatedByPreselection();
328             // activate the next obligatory widget
329             if (!isOperationCommitted)
330               aPropertyPanel->activateNextWidget(aFilledWidget);
331           }
332         }
333         else { // there is a greed widget
334           const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
335           std::string aFirstAttributeId = aWidgets.front()->attributeID();
336           // activate next widget after greeded if it is the first widget in the panel
337           // else the first panel widget is already activated by operation start
338           if (aFirstAttributeId == aGreedAttributeId)
339             aPostonedWidgetActivation = true;
340         }
341       }
342     } if (!isOperationCommitted) {
343       workshop()->updateCommandStatus();
344       aWorkshop->connectToPropertyPanel(true);
345       updateSketcherOnStart(aFOperation);
346       updatePresentationsOnStart(aFOperation);
347
348       // the objects of the current operation should be deactivated
349       QObjectPtrList anObjects;
350       anObjects.append(aFeature);
351       std::list<ResultPtr> aResults;
352       ModelAPI_Tools::allResults(aFeature, aResults);
353       std::list<ResultPtr>::const_iterator aIt;
354       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
355         anObjects.append(*aIt);
356       }
357       QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
358       for (; anIt != aLast; anIt++)
359         aWorkshop->deactivateActiveObject(*anIt, false);
360       if (anObjects.size() > 0) {
361         XGUI_Displayer* aDisplayer = aWorkshop->displayer();
362         aDisplayer->updateViewer();
363       }
364     }
365     if (aPostonedWidgetActivation) {
366       // if the widget is an empty in the chain of activated widgets, the current operation
367       // is restarted. It should be performed after functionality of the operation starting
368       aPropertyPanel->activateNextWidget(aFilledWidget);
369     }
370   }
371 }
372
373 void PartSet_Module::updateSketcherOnStart(ModuleBase_Operation* theOperation)
374 {
375   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
376     mySketchMgr->startSketch(theOperation);
377   }
378   else if (sketchMgr()->isNestedSketchOperation(theOperation)) {
379     mySketchMgr->startNestedSketch(theOperation);
380   }
381 }
382
383 void PartSet_Module::updatePresentationsOnStart(ModuleBase_Operation* theOperation)
384 {
385   ModuleBase_OperationFeature* aFOperation =
386     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
387   if (aFOperation) {
388     myCustomPrs->activate(aFOperation->feature(), ModuleBase_IModule::CustomizeArguments, true);
389     myCustomPrs->activate(aFOperation->feature(), ModuleBase_IModule::CustomizeResults, true);
390   }
391 }
392
393 void PartSet_Module::operationResumed(ModuleBase_Operation* theOperation)
394 {
395   ModuleBase_IModule::operationResumed(theOperation);
396
397   ModuleBase_OperationFeature* aFOperation =
398     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
399   if (aFOperation) {
400     myCustomPrs->activate(aFOperation->feature(), ModuleBase_IModule::CustomizeArguments, true);
401     myCustomPrs->activate(aFOperation->feature(), ModuleBase_IModule::CustomizeResults, true);
402   }
403 }
404
405 void PartSet_Module::operationStopped(ModuleBase_Operation* theOperation)
406 {
407   bool isModifiedArgs = myCustomPrs->deactivate(ModuleBase_IModule::CustomizeArguments, false);
408   bool isModifiedResults = myCustomPrs->deactivate(ModuleBase_IModule::CustomizeResults, false);
409   bool isModified = isModifiedArgs || isModifiedResults;
410
411   if (sketchMgr()->isNestedSketchOperation(theOperation)) {
412     mySketchMgr->stopNestedSketch(theOperation);
413   }
414   else if (PartSet_SketcherMgr::isSketchOperation(theOperation))
415     setDefaultConstraintShown();
416
417   //VSV: Viewer is updated on feature update and redisplay
418   if (isModified) {
419     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myWorkshop);
420     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
421     aDisplayer->updateViewer();
422   }
423
424   QMap<PartSet_Tools::ConstraintVisibleState, bool>::const_iterator
425     anIt = myHasConstraintShown.begin(), aLast = myHasConstraintShown.end();
426   for (; anIt != aLast; anIt++) {
427     mySketchMgr->updateBySketchParameters(anIt.key(), anIt.value());
428   }
429 }
430
431 ModuleBase_Operation* PartSet_Module::currentOperation() const
432 {
433   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
434   XGUI_OperationMgr* anOpMgr = aConnector->workshop()->operationMgr();
435   return anOpMgr->currentOperation();
436 }
437
438 bool PartSet_Module::canUndo() const
439 {
440   bool aCanUndo = false;
441   SessionPtr aMgr = ModelAPI_Session::get();
442   if (aMgr->hasModuleDocument() && aMgr->canUndo()) {
443     aCanUndo = !aMgr->isOperation();
444     if (!aCanUndo) // check the enable state additionally by sketch manager
445       aCanUndo = aMgr->canUndo();
446   }
447   return aCanUndo;
448 }
449
450 bool PartSet_Module::canRedo() const
451 {
452   bool aCanRedo = false;
453   SessionPtr aMgr = ModelAPI_Session::get();
454   if (aMgr->hasModuleDocument() && aMgr->canRedo()) {
455     aCanRedo = !aMgr->isOperation();
456     if (!aCanRedo) // check the enable state additionally by sketch manager
457       aCanRedo = aMgr->canRedo();
458   }
459   return aCanRedo;
460 }
461
462 bool PartSet_Module::canApplyAction(const ObjectPtr& theObject, const QString& theActionId) const
463 {
464   bool aValid = true;
465   if (theActionId == "MOVE_CMD") {
466     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
467     if (aFeature) {
468       ResultPtr aResult = ModuleBase_Tools::firstResult(aFeature);
469       // part features can not be moved in the history.
470       if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group())
471         aValid = false;
472     }
473   }
474   return aValid;
475 }
476
477 bool PartSet_Module::canEraseObject(const ObjectPtr& theObject) const
478 {
479   // the sketch manager put the restriction to the objects erase
480   return mySketchMgr->canEraseObject(theObject);
481 }
482
483 bool PartSet_Module::canDisplayObject(const ObjectPtr& theObject) const
484 {
485   // the sketch manager put the restriction to the objects display
486   return mySketchMgr->canDisplayObject(theObject);
487 }
488
489 /*void PartSet_Module::processHiddenObject(const std::list<ObjectPtr>& theObjects)
490 {
491   mySketchMgr->processHiddenObject(theObjects);
492 }*/
493
494 bool PartSet_Module::canActivateSelection(const ObjectPtr& theObject) const
495 {
496   bool aCanActivate = ModuleBase_IModule::canActivateSelection(theObject);
497
498   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
499   bool isSketchOp = PartSet_SketcherMgr::isSketchOperation(anOperation),
500        isNestedOp = sketchMgr()->isNestedSketchOperation(anOperation);
501   if (isSketchOp || isNestedOp) {
502     // in active sketch operation it is possible to activate operation object in selection
503     // in the edit operation, e.g. points of the line can be moved when the line is edited
504     ModuleBase_OperationFeature* aFOperation =
505       dynamic_cast<ModuleBase_OperationFeature*>(anOperation);
506     aCanActivate = aCanActivate || (aFOperation && aFOperation->isEditOperation());
507   }
508   return aCanActivate;
509 }
510
511 bool PartSet_Module::addViewerMenu(const QMap<QString, QAction*>& theStdActions,
512                                    QWidget* theParent,
513                                    QMap<int, QAction*>& theMenuActions) const
514 {
515   return myMenuMgr->addViewerMenu(theStdActions, theParent, theMenuActions);
516 }
517
518 void PartSet_Module::updateViewerMenu(const QMap<QString, QAction*>& theStdActions)
519 {
520   myMenuMgr->updateViewerMenu(theStdActions);
521 }
522
523 bool PartSet_Module::isActionEnableStateFixed(const int theActionId) const
524 {
525   bool isEnabledFixed = false;
526   if (theActionId == XGUI_ActionsMgr::AcceptAll &&
527       mySketchReentrantMgr->isInternalEditStarted())
528     isEnabledFixed = true;
529   return isEnabledFixed;
530 }
531
532 QString PartSet_Module::getFeatureError(const FeaturePtr& theFeature)
533 {
534   QString anError = ModuleBase_IModule::getFeatureError(theFeature);
535   if (anError.isEmpty())
536     anError = sketchMgr()->getFeatureError(theFeature);
537
538   return anError;
539 }
540
541 void PartSet_Module::grantedOperationIds(ModuleBase_Operation* theOperation,
542                                          QStringList& theIds) const
543 {
544   myMenuMgr->grantedOperationIds(theOperation, theIds);
545
546   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
547     XGUI_Workshop* aWorkshop = getWorkshop();
548     theIds.append(aWorkshop->contextMenuMgr()->action("DELETE_CMD")->text());
549   }
550 }
551
552 void PartSet_Module::activeSelectionModes(QIntList& theModes)
553 {
554   theModes.clear();
555   if (mySketchMgr->activeSketch().get())
556     PartSet_SketcherMgr::sketchSelectionModes(theModes);
557 }
558
559 void PartSet_Module::customSubShapesSelectionModes(QIntList& theTypes)
560 {
561   if (theTypes.contains(TopAbs_FACE))
562     theTypes.append(SketcherPrs_Tools::Sel_Sketch_Face);
563   if (theTypes.contains(TopAbs_WIRE))
564     theTypes.append(SketcherPrs_Tools::Sel_Sketch_Wire);
565 }
566
567 bool PartSet_Module::isMouseOverWindow()
568 {
569   return mySketchMgr->isMouseOverWindow();
570 }
571
572 bool PartSet_Module::isSketchNeutralPointActivated() const
573 {
574   bool isNeutralPoint = true;
575   if (sketchReentranceMgr()->isInternalEditStarted())
576     isNeutralPoint = false;
577   if (myIsOperationIsLaunched)
578     isNeutralPoint = false;
579
580   return isNeutralPoint;
581 }
582
583 void PartSet_Module::closeDocument()
584 {
585   myActivePartIndex = QModelIndex();
586   clearViewer();
587 }
588
589 void PartSet_Module::clearViewer()
590 {
591   myCustomPrs->clearPrs();
592
593   XGUI_Workshop* aWorkshop = getWorkshop();
594   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
595   aDisplayer->deactivateSelectionFilters();
596 }
597
598 void PartSet_Module::propertyPanelDefined(ModuleBase_Operation* theOperation)
599 {
600   ModuleBase_OperationFeature* aFOperation =
601     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
602   if (!aFOperation)
603     return;
604
605   ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
606   // we have to manually activate the sketch label in edit mode
607   if (PartSet_SketcherMgr::isSketchOperation(aFOperation) &&  (aFOperation->isEditOperation()))
608     aPanel->activateWidget(aPanel->modelWidgets().first());
609 }
610
611 bool PartSet_Module::createWidgets(ModuleBase_Operation* theOperation,
612                                    QList<ModuleBase_ModelWidget*>& theWidgets) const
613 {
614   bool aProcessed = false;
615
616   ModuleBase_OperationFeature* aFOperation =
617     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
618   XGUI_Workshop* aWorkshop = getWorkshop();
619   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
620   if (mySketchMgr->activeSketch().get() && aFOperation && aPropertyPanel) {
621     ModuleBase_ISelection* aSelection = workshop()->selection();
622     // click on a point in sketch leads here with the point is highlighted, not yet selected
623     QList<ModuleBase_ViewerPrsPtr> aPreselection = aSelection->getHighlighted();
624     if (aPreselection.size() == 1) {
625       ModuleBase_ViewerPrsPtr aSelectedPrs = aPreselection[0];
626       ObjectPtr anObject = aSelectedPrs->object();
627
628       FeaturePtr aFeature = ModelAPI_Feature::feature(anObject);
629       FeaturePtr anOpFeature = aFOperation->feature();
630       GeomShapePtr aShape = aSelectedPrs->shape();
631       // click on the digit of dimension constrain comes here
632       // with an empty shape, so we need the check
633       if (aFeature == anOpFeature && aShape.get() && !aShape->isNull()) {
634         // if feature has only one result and shape of result is equal to selected shape
635         // this attribute is not processed. It is a case of Sketch Point.
636         if (aFeature->results().size() == 1) {
637           ResultPtr aResult = aFeature->results().front();
638           if (aResult.get() && aResult->shape()->isEqual(aShape))
639             return aProcessed;
640         }
641         const TopoDS_Shape& aTDShape = aShape->impl<TopoDS_Shape>();
642         AttributePtr anAttribute = PartSet_Tools::findAttributeBy2dPoint(anObject, aTDShape,
643                                                                mySketchMgr->activeSketch());
644         if (anAttribute.get()) {
645           QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
646           ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), workshop());
647
648           const std::string anAttributeId = anAttribute->id();
649           aFactory.createWidget(aPropertyPanel->contentWidget(), anAttributeId);
650
651           theWidgets = aFactory.getModelWidgets();
652           // it is possible that the point does not present in XML definition,
653           // in this case, we assume that it is not processed by this module
654           // e.g. "Intersection point" feature
655           aProcessed = !theWidgets.isEmpty();
656         }
657       }
658     }
659   }
660   return aProcessed;
661 }
662
663 void PartSet_Module::onSelectionChanged()
664 {
665   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
666   if (!aOperation)
667     return;
668
669   bool isSketcherOp = false;
670   // An edit operation is enable only if the current opeation is the sketch operation
671   if (mySketchMgr->activeSketch()) {
672     if (PartSet_Tools::sketchPlane(mySketchMgr->activeSketch()))
673       isSketcherOp = PartSet_SketcherMgr::isSketchOperation(aOperation);
674   }
675   if (isSketcherOp) {
676     // Editing of constraints can be done on selection
677     ModuleBase_ISelection* aSelect = myWorkshop->selection();
678     QList<ModuleBase_ViewerPrsPtr> aSelected = aSelect->getSelected();
679     if (aSelected.size() == 1) {
680       ModuleBase_ViewerPrsPtr aPrs = aSelected.first();
681       ObjectPtr aObject = aPrs->object();
682       FeaturePtr aFeature = ModelAPI_Feature::feature(aObject);
683       if (aFeature) {
684         std::string aId = aFeature->getKind();
685         if ((aId == SketchPlugin_ConstraintRadius::ID()) ||
686             (aId == SketchPlugin_ConstraintLength::ID()) ||
687             (aId == SketchPlugin_ConstraintDistance::ID()) ||
688             (aId == SketchPlugin_ConstraintAngle::ID())) {
689           editFeature(aFeature);
690         }
691       }
692     }
693   }
694 }
695
696 void PartSet_Module::onKeyRelease(ModuleBase_IViewWindow* theWnd, QKeyEvent* theEvent)
697 {
698   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
699   XGUI_OperationMgr* anOpMgr = aConnector->workshop()->operationMgr();
700   anOpMgr->onKeyReleased(theWnd->viewPort(), theEvent);
701 }
702
703 ModuleBase_ModelWidget* PartSet_Module::createWidgetByType(const std::string& theType,
704                                                            QWidget* theParent,
705                                                            Config_WidgetAPI* theWidgetApi)
706 {
707   ModuleBase_IWorkshop* aWorkshop = workshop();
708   XGUI_Workshop* aXUIWorkshop = getWorkshop();
709   ModuleBase_ModelWidget* aWgt = NULL;
710   if (theType == "sketch-start-label") {
711     PartSet_WidgetSketchLabel* aLabelWgt = new PartSet_WidgetSketchLabel(theParent, aWorkshop,
712                                                                theWidgetApi, myHasConstraintShown);
713     connect(aLabelWgt, SIGNAL(planeSelected(const std::shared_ptr<GeomAPI_Pln>&)),
714       mySketchMgr, SLOT(onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>&)));
715     connect(aLabelWgt, SIGNAL(showConstraintToggled(int, bool)),
716       mySketchMgr, SLOT(onShowConstraintsToggle(int, bool)));
717     aWgt = aLabelWgt;
718   } else if (theType == "sketch-2dpoint_selector") {
719     PartSet_WidgetPoint2D* aPointWgt = new PartSet_WidgetPoint2D(theParent, aWorkshop,
720                                                                  theWidgetApi);
721     aPointWgt->setSketch(mySketchMgr->activeSketch());
722     connect(aPointWgt, SIGNAL(vertexSelected()), sketchReentranceMgr(), SLOT(onVertexSelected()));
723     aWgt = aPointWgt;
724   }else if (theType == "sketch-2dpoint_flyout_selector") {
725     PartSet_WidgetPoint2DFlyout* aPointWgt = new PartSet_WidgetPoint2DFlyout(theParent, aWorkshop,
726                                                                              theWidgetApi);
727     aPointWgt->setSketch(mySketchMgr->activeSketch());
728     connect(aPointWgt, SIGNAL(vertexSelected()), sketchReentranceMgr(), SLOT(onVertexSelected()));
729     aWgt = aPointWgt;
730   } else if (theType == "point2ddistance") {
731     PartSet_WidgetPoint2dDistance* aDistanceWgt = new PartSet_WidgetPoint2dDistance(theParent,
732                                                                      aWorkshop, theWidgetApi);
733     aDistanceWgt->setSketch(mySketchMgr->activeSketch());
734     aWgt = aDistanceWgt;
735   } else if (theType == "sketch_shape_selector") {
736     PartSet_WidgetShapeSelector* aShapeSelectorWgt =
737                           new PartSet_WidgetShapeSelector(theParent, aWorkshop, theWidgetApi);
738     aShapeSelectorWgt->setSketcher(mySketchMgr->activeSketch());
739     aWgt = aShapeSelectorWgt;
740   } else if (theType == "sketch_multi_selector") {
741     PartSet_WidgetMultiSelector* aShapeSelectorWgt =
742                           new PartSet_WidgetMultiSelector(theParent, aWorkshop, theWidgetApi);
743     aShapeSelectorWgt->setSketcher(mySketchMgr->activeSketch());
744     aWgt = aShapeSelectorWgt;
745   }
746   else if (theType == "sketch_sub_shape_selector") {
747     PartSet_WidgetSubShapeSelector* aSubShapeSelectorWgt =
748                           new PartSet_WidgetSubShapeSelector(theParent, aWorkshop, theWidgetApi);
749     aSubShapeSelectorWgt->setSketcher(mySketchMgr->activeSketch());
750     aWgt = aSubShapeSelectorWgt;
751   }
752   else if (theType == WDG_DOUBLEVALUE_EDITOR) {
753     aWgt = new PartSet_WidgetEditor(theParent, aWorkshop, theWidgetApi);
754   } else if (theType == "export_file_selector") {
755     aWgt = new PartSet_WidgetFileSelector(theParent, aWorkshop, theWidgetApi);
756   } else if (theType == "sketch_launcher") {
757     aWgt = new PartSet_WidgetSketchCreator(theParent, this, theWidgetApi);
758   } else if (theType == "module_choice") {
759     aWgt = new PartSet_WidgetChoice(theParent, theWidgetApi);
760     connect(aWgt, SIGNAL(itemSelected(ModuleBase_ModelWidget*, int)),
761             this, SLOT(onChoiceChanged(ModuleBase_ModelWidget*, int)));
762   }
763   return aWgt;
764 }
765
766 ModuleBase_ModelWidget* PartSet_Module::activeWidget() const
767 {
768   ModuleBase_ModelWidget* anActiveWidget = 0;
769
770   anActiveWidget = mySketchReentrantMgr->internalActiveWidget();
771   if (!anActiveWidget) {
772     ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
773     if (aOperation) {
774       ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
775       anActiveWidget = aPanel ? aPanel->activeWidget() : 0;
776     }
777   }
778   return anActiveWidget;
779 }
780
781 bool PartSet_Module::deleteObjects()
782 {
783   bool isProcessed = false;
784
785   XGUI_Workshop* aWorkshop = getWorkshop();
786   XGUI_OperationMgr* anOpMgr = aWorkshop->operationMgr();
787
788   //SessionPtr aMgr = ModelAPI_Session::get();
789   // 1. check whether the delete should be processed in the module
790   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
791   bool isSketchOp = PartSet_SketcherMgr::isSketchOperation(anOperation),
792        isNestedOp = sketchMgr()->isNestedSketchOperation(anOperation);
793   if (isSketchOp || isNestedOp) {
794     isProcessed = true;
795     // 2. find selected presentations
796     // selected objects should be collected before the current operation abort because
797     // the abort leads to selection lost on constraint objects. It can be corrected after #386 issue
798     ModuleBase_ISelection* aSel = workshop()->selection();
799     QObjectPtrList aSelectedObj = aSel->selectedPresentations();
800     // if there are no selected objects in the viewer, that means that the selection in another
801     // place cased this method. It is necessary to return the false value to understande in above
802     // method that delete is not processed
803     if (aSelectedObj.count() == 0)
804       return false;
805
806     // avoid delete of the objects, which are not belong to the current sketch
807     // in order to do not delete results of other sketches
808     QObjectPtrList aSketchObjects;
809     QObjectPtrList::const_iterator anIt = aSelectedObj.begin(), aLast = aSelectedObj.end();
810     for ( ; anIt != aLast; anIt++) {
811       ObjectPtr anObject = *anIt;
812       if (mySketchMgr->isObjectOfSketch(anObject)) {
813         // sketch feature should be used in this list because workshop deletes features only
814         // results are skipped
815         FeaturePtr aSketchFeature = ModelAPI_Feature::feature(anObject);
816         aSketchObjects.append(aSketchFeature);
817       }
818     }
819     // if the selection contains only local selected presentations from other sketches,
820     // the Delete operation should not be done at all
821     if (aSketchObjects.size() == 0)
822       return true;
823
824     // 3. start operation
825     QString aDescription = aWorkshop->contextMenuMgr()->action("DELETE_CMD")->text();
826     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, this);
827
828     // the active nested sketch operation should be aborted unconditionally
829     // the Delete action should be additionally granted for the Sketch operation
830     // in order to do not abort/commit it
831     if (!anOpMgr->canStartOperation(anOpAction->id()))
832       return true; // the objects are processed but can not be deleted
833
834     anOpMgr->startOperation(anOpAction);
835
836     // WORKAROUND, should be done to avoid viewer highlight update after deletetion of objects
837     // the problem is in AIS Dimensions recompute
838     // if a line and the dim are removed, line is the first
839     // it causes the AIS recompute, where the base line is null,
840     // the result is empty AIS in the viewer
841     XGUI_Tools::workshop(myWorkshop)->selector()->clearSelection();
842
843     // 4. delete features
844     // sketch feature should be skipped, only sub-features can be removed
845     // when sketch operation is active
846     aWorkshop->deleteFeatures(aSketchObjects);
847     // 5. stop operation
848     anOpMgr->commitOperation();
849   }
850   return isProcessed;
851 }
852
853 void PartSet_Module::onFeatureTriggered()
854 {
855   // is commented for imp: Unpressing the button of the current action must behave like
856   // a validation if the entity can be created (instead of Cancel, as currently)
857   /*QAction* aCmd = dynamic_cast<QAction*>(sender());
858   if (aCmd->isCheckable() && aCmd->isChecked()) {
859     // 1. check whether the delete should be processed in the module
860     ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
861     bool isNestedOp = myModule->sketchMgr()->isNestedCreateOperation(anOperation);
862     if (isNestedOp) {
863       // in case if in the viewer nothing is displayed, the create operation should not be
864       // comitted even if all values of the feature are initialized
865       if (!mySketchMgr->canDisplayCurrentCreatedFeature()) {
866         // the action information should be saved before the operation is aborted
867         // because this abort leads to update command status, which unchecks this action
868         anOperation->abort();
869         launchOperation(aCmd->data().toString());
870       }
871     }
872   }*/
873   ModuleBase_IModule::onFeatureTriggered();
874 }
875
876 void PartSet_Module::editFeature(FeaturePtr theFeature)
877 {
878   storeConstraintsState(theFeature->getKind());
879   ModuleBase_IModule::editFeature(theFeature);
880 }
881
882 bool PartSet_Module::canCommitOperation() const
883 {
884   return true;
885 }
886
887 void PartSet_Module::launchOperation(const QString& theCmdId)
888 {
889   myIsOperationIsLaunched = true;
890   storeConstraintsState(theCmdId.toStdString());
891   updateConstraintsState(theCmdId.toStdString());
892
893   ModuleBase_IModule::launchOperation(theCmdId);
894
895   myIsOperationIsLaunched = false;
896 }
897
898 void PartSet_Module::storeConstraintsState(const std::string& theFeatureKind)
899 {
900   if (myWorkshop->currentOperation() &&
901       myWorkshop->currentOperation()->id().toStdString() == SketchPlugin_Sketch::ID()) {
902     const QMap<PartSet_Tools::ConstraintVisibleState, bool>& aShownStates =
903                                                   mySketchMgr->showConstraintStates();
904     myHasConstraintShown = aShownStates;
905   }
906 }
907
908 void PartSet_Module::updateConstraintsState(const std::string& theFeatureKind)
909 {
910   if (PartSet_SketcherMgr::constraintsIdList().contains(theFeatureKind.c_str()) ||
911       PartSet_SketcherMgr::replicationsIdList().contains(theFeatureKind.c_str())) {
912     // Show constraints if a constraint was anOperation
913     mySketchMgr->updateBySketchParameters(PartSet_Tools::Geometrical, true);
914     mySketchMgr->updateBySketchParameters(PartSet_Tools::Dimensional, true);
915     mySketchMgr->updateBySketchParameters(PartSet_Tools::Expressions,
916                                           myHasConstraintShown[PartSet_Tools::Expressions]);
917   }
918 }
919
920 void PartSet_Module::onObjectDisplayed(ObjectPtr theObject, AISObjectPtr theAIS)
921 {
922   Handle(AIS_InteractiveObject) anAIS = theAIS->impl<Handle(AIS_InteractiveObject)>();
923   if (!anAIS.IsNull()) {
924     Handle(AIS_InteractiveContext) aCtx = anAIS->GetContext();
925     Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(anAIS);
926     if (!aDim.IsNull()) {
927       aCtx->SetZLayer(aDim, myVisualLayerId);
928     } else {
929       Handle(SketcherPrs_SymbolPrs) aCons = Handle(SketcherPrs_SymbolPrs)::DownCast(anAIS);
930       if (!aCons.IsNull())
931         aCtx->SetZLayer(aCons, myVisualLayerId);
932     }
933   }
934 }
935
936 void PartSet_Module::onBeforeObjectErase(ObjectPtr theObject, AISObjectPtr theAIS)
937 {
938   // this is obsolete
939   // it should be recomputed in order to disappear in the viewer if the corresponded object
940   // is erased
941   //if (myCustomPrs->isActive())
942   //  myCustomPrs->redisplay(theObject, false);
943 }
944
945 void PartSet_Module::onViewTransformed(int theTrsfType)
946 {
947   // Set length of arrows constant in pixel size
948   // if the operation is panning or rotate or panglobal then do nothing
949   if ((theTrsfType == 1) || (theTrsfType == 3) || (theTrsfType == 4))
950     return;
951   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
952   Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
953   if (aContext.IsNull())
954     return;
955
956   //Handle(V3d_View) aView = aViewer->activeView();
957
958   XGUI_Workshop* aWorkshop = getWorkshop();
959   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
960   Handle(V3d_Viewer) aV3dViewer = aContext->CurrentViewer();
961   Handle(V3d_View) aView;
962   double aScale = 0;
963   for (aV3dViewer->InitDefinedViews();
964        aV3dViewer->MoreDefinedViews();
965        aV3dViewer->NextDefinedViews()) {
966     Handle(V3d_View) aV = aV3dViewer->DefinedView();
967     double aS = aV->Scale();
968     if (aS > aScale) {
969       aScale = aS;
970       aView = aV;
971     }
972   }
973   if (aView.IsNull())
974     return;
975   double aLen = aView->Convert(SketcherPrs_Tools::getDefaultArrowSize());
976
977   double aPrevLen = SketcherPrs_Tools::getArrowSize();
978   SketcherPrs_Tools::setArrowSize(aLen);
979   const double aPrevScale = aViewer->Scale(aViewer->activeView());
980   const double aCurScale = aViewer->activeView()->Camera()->Scale();
981   aViewer->SetScale(aViewer->activeView(), aCurScale);
982   SketcherPrs_Tools::setTextHeight (aCurScale / aPrevScale * SketcherPrs_Tools::getTextHeight());
983   bool isModified = false;
984   QList<AISObjectPtr> aPrsList = aDisplayer->displayedPresentations();
985   foreach (AISObjectPtr aAIS, aPrsList) {
986     Handle(AIS_InteractiveObject) aAisObj = aAIS->impl<Handle(AIS_InteractiveObject)>();
987
988     Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(aAisObj);
989     if (!aDim.IsNull()) {
990       aDim->DimensionAspect()->ArrowAspect()->SetLength(aLen);
991       aContext->Redisplay(aDim, false);
992       isModified = true;
993     }
994   }
995   if (isModified)
996     aDisplayer->updateViewer();
997 }
998
999 bool PartSet_Module::isCustomPrsActivated(const ModuleBase_CustomizeFlag& theFlag) const
1000 {
1001   return myCustomPrs->isActive(theFlag);
1002 }
1003
1004 void PartSet_Module::activateCustomPrs(const FeaturePtr& theFeature,
1005                                        const ModuleBase_CustomizeFlag& theFlag,
1006                                        const bool theUpdateViewer)
1007 {
1008   myCustomPrs->activate(theFeature, theFlag, theUpdateViewer);
1009 }
1010
1011 void PartSet_Module::deactivateCustomPrs(const ModuleBase_CustomizeFlag& theFlag,
1012                                          const bool theUpdateViewer)
1013 {
1014   myCustomPrs->deactivate(theFlag, theUpdateViewer);
1015 }
1016
1017 bool PartSet_Module::customisePresentation(ResultPtr theResult, AISObjectPtr thePrs,
1018                                            std::shared_ptr<GeomAPI_ICustomPrs> theCustomPrs)
1019 {
1020   bool aCustomized = false;
1021
1022   XGUI_Workshop* aWorkshop = getWorkshop();
1023   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1024   ObjectPtr anObject = aDisplayer->getObject(thePrs);
1025   if (!anObject)
1026     return aCustomized;
1027
1028   if (!theResult.get()) {
1029     bool isConflicting = myOverconstraintListener->isConflictingObject(anObject);
1030     // customize sketch symbol presentation
1031     if (thePrs.get()) {
1032       Handle(AIS_InteractiveObject) anAISIO = thePrs->impl<Handle(AIS_InteractiveObject)>();
1033       if (!anAISIO.IsNull()) {
1034         if (!Handle(SketcherPrs_SymbolPrs)::DownCast(anAISIO).IsNull()) {
1035           Handle(SketcherPrs_SymbolPrs) aPrs = Handle(SketcherPrs_SymbolPrs)::DownCast(anAISIO);
1036           if (!aPrs.IsNull()) {
1037             std::vector<int> aColor;
1038             myOverconstraintListener->getConflictingColor(aColor);
1039             aPrs->SetConflictingConstraint(isConflicting, aColor);
1040             aCustomized = true;
1041           }
1042         } else if (!Handle(SketcherPrs_Coincident)::DownCast(anAISIO).IsNull()) {
1043           Handle(SketcherPrs_Coincident) aPrs = Handle(SketcherPrs_Coincident)::DownCast(anAISIO);
1044           if (!aPrs.IsNull()) {
1045             std::vector<int> aColor;
1046             myOverconstraintListener->getConflictingColor(aColor);
1047             aPrs->SetConflictingConstraint(isConflicting, aColor);
1048             aCustomized = true;
1049           }
1050         }
1051       }
1052     }
1053     // customize sketch dimension constraint presentation
1054     if (!aCustomized) {
1055       std::vector<int> aColor;
1056       if (isConflicting) {
1057         myOverconstraintListener->getConflictingColor(aColor);
1058       }
1059       if (aColor.empty())
1060         XGUI_CustomPrs::getDefaultColor(anObject, true, aColor);
1061       if (!aColor.empty()) {
1062         aCustomized = thePrs->setColor(aColor[0], aColor[1], aColor[2]);
1063       }
1064     }
1065   }
1066   // customize dimentional constrains
1067   sketchMgr()->customizePresentation(anObject);
1068
1069   return aCustomized;
1070 }
1071
1072 bool PartSet_Module::customizeObject(ObjectPtr theObject, const ModuleBase_CustomizeFlag& theFlag,
1073                                      const bool theUpdateViewer)
1074 {
1075   bool isRedisplayed = false;
1076   if (myCustomPrs->isActive(theFlag))
1077     isRedisplayed = myCustomPrs->redisplay(theObject, theFlag, theUpdateViewer);
1078
1079   return isRedisplayed;
1080 }
1081
1082 void PartSet_Module::customizeObjectBrowser(QWidget* theObjectBrowser)
1083 {
1084   XGUI_ObjectsBrowser* aOB = dynamic_cast<XGUI_ObjectsBrowser*>(theObjectBrowser);
1085   if (aOB) {
1086     QLabel* aLabel = aOB->activeDocLabel();
1087     aLabel->installEventFilter(myMenuMgr);
1088     connect(aLabel, SIGNAL(customContextMenuRequested(const QPoint&)),
1089           SLOT(onActiveDocPopup(const QPoint&)));
1090     aOB->treeView()->setExpandsOnDoubleClick(false);
1091     connect(aOB->treeView(), SIGNAL(doubleClicked(const QModelIndex&)),
1092       SLOT(onTreeViewDoubleClick(const QModelIndex&)));
1093
1094     Events_Loop* aLoop = Events_Loop::loop();
1095     aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1096   }
1097 }
1098
1099 void PartSet_Module::onActiveDocPopup(const QPoint& thePnt)
1100 {
1101   SessionPtr aMgr = ModelAPI_Session::get();
1102   QAction* aActivatePartAction = myMenuMgr->action("ACTIVATE_PARTSET_CMD");
1103
1104   XGUI_Workshop* aWorkshop = getWorkshop();
1105   QLabel* aHeader = aWorkshop->objectBrowser()->activeDocLabel();
1106
1107   aActivatePartAction->setEnabled((aMgr->activeDocument() != aMgr->moduleDocument()));
1108
1109   QMenu aMenu;
1110   aMenu.addAction(aActivatePartAction);
1111   aMenu.exec(aHeader->mapToGlobal(thePnt));
1112 }
1113
1114 Handle(AIS_InteractiveObject) PartSet_Module::createPresentation(const ResultPtr& theResult)
1115 {
1116   return mySketchMgr->createPresentation(theResult);
1117 }
1118
1119
1120 ObjectPtr PartSet_Module::findPresentedObject(const AISObjectPtr& theAIS) const
1121 {
1122   ObjectPtr anObject;
1123   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1124   if (aOperation) {
1125     /// If last line finished on vertex the lines creation sequence has to be break
1126     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
1127     if (aPanel) {
1128       ModuleBase_ModelWidget* anActiveWidget = aPanel->activeWidget();
1129       // if there is an active widget, find the presented object in it
1130       if (!anActiveWidget)
1131         anActiveWidget = aPanel->preselectionWidget();
1132
1133       ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
1134                                                                              (anActiveWidget);
1135       if (aWidgetValidated)
1136         anObject = aWidgetValidated->findPresentedObject(theAIS);
1137     }
1138   }
1139   return anObject;
1140 }
1141
1142 bool PartSet_Module::canBeShaded(Handle(AIS_InteractiveObject) theAIS) const
1143 {
1144   bool aCanBeShaged = true;
1145
1146   Handle(PartSet_ResultSketchPrs) aPrs = Handle(PartSet_ResultSketchPrs)::DownCast(theAIS);
1147   if (!aPrs.IsNull())
1148     aCanBeShaged = false;
1149
1150   return aCanBeShaged;
1151 }
1152
1153 void PartSet_Module::addObjectBrowserMenu(QMenu* theMenu) const
1154 {
1155   QObjectPtrList aObjects = myWorkshop->selection()->selectedObjects();
1156   int aSelected = aObjects.size();
1157   SessionPtr aMgr = ModelAPI_Session::get();
1158   QAction* aActivatePartAction = myMenuMgr->action("ACTIVATE_PART_CMD");
1159
1160   ModuleBase_Operation* aCurrentOp = myWorkshop->currentOperation();
1161   if (aSelected == 1) {
1162     bool hasResult = false;
1163     bool hasFeature = false;
1164     bool hasParameter = false;
1165     bool hasCompositeOwner = false;
1166     ModuleBase_Tools::checkObjects(aObjects, hasResult, hasFeature, hasParameter,
1167                                    hasCompositeOwner);
1168     ObjectPtr aObject = aObjects.first();
1169     if (aObject) {
1170       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1171       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1172       bool isPart = aPart.get() ||
1173         (aFeature.get() && (aFeature->getKind() == PartSetPlugin_Part::ID()));
1174       if (isPart) {
1175         DocumentPtr aPartDoc;
1176         if (!aPart.get()) {
1177           aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFeature->firstResult());
1178         }
1179         if (aPart.get()) // this may be null is Part feature is disabled
1180           aPartDoc = aPart->partDoc();
1181
1182         theMenu->addAction(aActivatePartAction);
1183         aActivatePartAction->setEnabled((aMgr->activeDocument() != aPartDoc));
1184
1185       } else if (aObject->document() == aMgr->activeDocument()) {
1186         if (hasParameter || hasFeature) {
1187           myMenuMgr->action("EDIT_CMD")->setEnabled(true);
1188           theMenu->addAction(myMenuMgr->action("EDIT_CMD"));
1189           if (aCurrentOp && aFeature.get()) {
1190             if (aCurrentOp->id().toStdString() == aFeature->getKind())
1191               myMenuMgr->action("EDIT_CMD")->setEnabled(false);
1192           }
1193         }
1194       }
1195
1196       ResultBodyPtr aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1197       if( aResult.get() )
1198         theMenu->addAction(myMenuMgr->action("SELECT_PARENT_CMD"));
1199     }
1200   }
1201   bool aNotDeactivate = (aCurrentOp == 0);
1202   if (!aNotDeactivate) {
1203     aActivatePartAction->setEnabled(false);
1204   }
1205 }
1206
1207 #define EXPAND_PARENT(OBJ) \
1208 QModelIndex aObjIndex = aDataModel->objectIndex(OBJ); \
1209 if (aObjIndex.isValid()) { \
1210   QModelIndex aParent = aObjIndex.parent(); \
1211   int aCount = aDataModel->rowCount(aParent); \
1212   if (aCount == 1) \
1213     aTreeView->setExpanded(aParent, true); \
1214 }
1215
1216
1217 void PartSet_Module::processEvent(const std::shared_ptr<Events_Message>& theMessage)
1218 {
1219   if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_DOCUMENT_CHANGED)) {
1220     // Do not change activation of parts if an operation active
1221     static QStringList aAllowActivationList;
1222     if (aAllowActivationList.isEmpty())
1223       aAllowActivationList <<
1224       QString(PartSetPlugin_Part::ID().c_str()) <<
1225       QString(PartSetPlugin_Duplicate::ID().c_str()) <<
1226       QString(PartSetPlugin_Remove::ID().c_str());
1227     if (myWorkshop->currentOperation() &&
1228       (!aAllowActivationList.contains(myWorkshop->currentOperation()->id())))
1229       return;
1230     XGUI_Workshop* aWorkshop = getWorkshop();
1231     XGUI_DataTree* aTreeView = aWorkshop->objectBrowser()->treeView();
1232     QLabel* aLabel = aWorkshop->objectBrowser()->activeDocLabel();
1233     QPalette aPalet = aLabel->palette();
1234
1235     SessionPtr aMgr = ModelAPI_Session::get();
1236     DocumentPtr aActiveDoc = aMgr->activeDocument();
1237     if (myActivePartIndex.isValid())
1238       aTreeView->setExpanded(myActivePartIndex, false);
1239     XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1240     myActivePartIndex = aDataModel->documentRootIndex(aActiveDoc);
1241     if (myActivePartIndex.isValid())
1242       aTreeView->setExpanded(myActivePartIndex, true);
1243
1244     aLabel->setPalette(aPalet);
1245     aWorkshop->updateCommandStatus();
1246
1247     // Update displayed objects in order to update active color
1248     XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1249     QObjectPtrList aObjects = aDisplayer->displayedObjects();
1250     bool aHidden;
1251     foreach(ObjectPtr aObj, aObjects) {
1252       aHidden = !aObj->data() || !aObj->data()->isValid() ||
1253         aObj->isDisabled() || (!aObj->isDisplayed());
1254       if (!aHidden)
1255         aDisplayer->redisplay(aObj, false);
1256     }
1257     aDisplayer->updateViewer();
1258   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
1259     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
1260         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
1261     std::set<ObjectPtr> aObjects = aUpdMsg->objects();
1262
1263     ObjectPtr aConstrObj;
1264     ObjectPtr aResultObj;
1265     std::set<ObjectPtr>::const_iterator aIt;
1266     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
1267     for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
1268       ObjectPtr aObject = (*aIt);
1269       if ((!aResultObj.get()) && (aObject->groupName() == ModelAPI_ResultBody::group())
1270           && (aObject->document() != aRootDoc))
1271         aResultObj = aObject;
1272       if ((!aConstrObj.get()) && (aObject->groupName() == ModelAPI_ResultConstruction::group())
1273           && (aObject->document() != aRootDoc))
1274         aConstrObj = aObject;
1275       if (aResultObj.get() && aConstrObj.get())
1276         break;
1277     }
1278
1279     if (aResultObj.get() || aConstrObj.get()) {
1280       XGUI_Workshop* aWorkshop = getWorkshop();
1281       XGUI_DataTree* aTreeView = aWorkshop->objectBrowser()->treeView();
1282       XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1283
1284       if (aResultObj.get()) {
1285         EXPAND_PARENT(aResultObj)
1286       }
1287       if (aConstrObj.get()) {
1288         EXPAND_PARENT(aConstrObj)
1289       }
1290     }
1291   }
1292 }
1293
1294 void PartSet_Module::onTreeViewDoubleClick(const QModelIndex& theIndex)
1295 {
1296   if (myWorkshop->currentOperation()) // Do not change activation of parts if an operation active
1297     return;
1298   SessionPtr aMgr = ModelAPI_Session::get();
1299   if (!theIndex.isValid()) {
1300     // It seems that this code is obsolete
1301     //aMgr->setActiveDocument(aMgr->moduleDocument());
1302     return;
1303   }
1304   if (theIndex.column() != 0) // Use only first column
1305     return;
1306
1307   XGUI_Workshop* aWorkshop = getWorkshop();
1308   XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1309   // De not use non editable Indexes
1310   if ((aDataModel->flags(theIndex) & Qt::ItemIsSelectable) == 0)
1311     return;
1312   ObjectPtr aObj = aDataModel->object(theIndex);
1313
1314   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1315   if (!aPart.get()) { // Probably this is Feature
1316     FeaturePtr aPartFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
1317     if (aPartFeature.get() && (aPartFeature->getKind() == PartSetPlugin_Part::ID())) {
1318       aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aPartFeature->firstResult());
1319     }
1320   }
1321   if (aPart.get()) { // if this is a part
1322     if (aPart->partDoc() == aMgr->activeDocument()) {
1323       myMenuMgr->activatePartSet();
1324     } else {
1325       myMenuMgr->activatePart(aPart);
1326     }
1327   }
1328 }
1329
1330
1331 void PartSet_Module::onViewCreated(ModuleBase_IViewWindow*)
1332 {
1333   // z layer is created for all started operations in order to visualize operation AIS presentation
1334   // over the object
1335   Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
1336   if (aContext.IsNull())
1337     return;
1338
1339   Handle(V3d_Viewer) aViewer = aContext->CurrentViewer();
1340   if (myVisualLayerId == 0) {
1341     if (myVisualLayerId == 0)
1342       aViewer->AddZLayer(myVisualLayerId);
1343   } else {
1344     TColStd_SequenceOfInteger aZList;
1345     aViewer->GetAllZLayers(aZList);
1346     bool aFound = false;
1347     for (int i = 1; i <= aZList.Length(); i++) {
1348       if (aZList(i) == myVisualLayerId) {
1349         aFound = true;
1350         break;
1351       }
1352     }
1353     if (!aFound)
1354       aViewer->AddZLayer(myVisualLayerId);
1355   }
1356   // if there is an active operation with validated widget,
1357   // the filters of this widget should be activated in the created view
1358   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1359   if (aOperation) {
1360     ModuleBase_ModelWidget* anActiveWidget = activeWidget();
1361     if (anActiveWidget) {
1362       ModuleBase_WidgetSelector* aWSelector =
1363         dynamic_cast<ModuleBase_WidgetSelector*>(anActiveWidget);
1364       if (aWSelector)
1365         aWSelector->activateSelectionAndFilters(true);
1366     }
1367   }
1368 }
1369
1370 //******************************************************
1371 void PartSet_Module::widgetStateChanged(int thePreviousState)
1372 {
1373   mySketchMgr->widgetStateChanged(thePreviousState);
1374 }
1375
1376 bool PartSet_Module::processEnter(const std::string& thePreviousAttributeID)
1377 {
1378   return mySketchReentrantMgr->processEnter(thePreviousAttributeID);
1379 }
1380
1381 //******************************************************
1382 void PartSet_Module::beforeOperationStopped(ModuleBase_Operation* theOperation)
1383 {
1384   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
1385     mySketchMgr->stopSketch(theOperation);
1386   }
1387 }
1388
1389 //******************************************************
1390 GeomShapePtr PartSet_Module::findShape(const AttributePtr& theAttribute)
1391 {
1392   GeomShapePtr aGeomShape;
1393
1394   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
1395   if (anOperation && sketchMgr()->isNestedSketchOperation(anOperation)) {
1396     aGeomShape = PartSet_Tools::findShapeBy2DPoint(theAttribute, myWorkshop);
1397   }
1398   return aGeomShape;
1399 }
1400
1401 //******************************************************
1402 AttributePtr PartSet_Module::findAttribute(const ObjectPtr& theObject,
1403                                            const GeomShapePtr& theGeomShape)
1404 {
1405   AttributePtr anAttribute;
1406   GeomShapePtr aGeomShape = theGeomShape;
1407   if (!aGeomShape.get()) {
1408     // processing shape of result, e.g. sketch circle center is selected, this is a result
1409     // the geom shape is empty, the shape of result should be used
1410     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1411     if (aResult.get()) {
1412       aGeomShape = aResult->shape();
1413     }
1414   }
1415
1416   if (aGeomShape.get()) {
1417     TopoDS_Shape aTDSShape = aGeomShape->impl<TopoDS_Shape>();
1418     return PartSet_Tools::findAttributeBy2dPoint(theObject, aTDSShape,
1419                                                  mySketchMgr->activeSketch());
1420   }
1421   return anAttribute;
1422 }
1423
1424 //******************************************************
1425 void PartSet_Module::onChoiceChanged(ModuleBase_ModelWidget* theWidget,
1426                                      int theIndex)
1427 {
1428   PartSet_WidgetChoice* aChoiceWidget = dynamic_cast<PartSet_WidgetChoice*>(theWidget);
1429   if (!aChoiceWidget)
1430     return;
1431
1432   QString aChoiceTitle = aChoiceWidget->getPropertyPanelTitle(theIndex);
1433   if (!aChoiceTitle.isEmpty()) {
1434     ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1435     if (!aOperation)
1436       return;
1437     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
1438     if (aPanel)
1439       aPanel->setWindowTitle(aChoiceTitle);
1440   }
1441 }
1442
1443 //******************************************************
1444 XGUI_Workshop* PartSet_Module::getWorkshop() const
1445 {
1446   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
1447   return aConnector->workshop();
1448 }
1449
1450 //******************************************************
1451 void PartSet_Module::setDefaultConstraintShown()
1452 {
1453   myHasConstraintShown[PartSet_Tools::Geometrical] = true;
1454   myHasConstraintShown[PartSet_Tools::Dimensional] = true;
1455   myHasConstraintShown[PartSet_Tools::Expressions] = false;
1456 }