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