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