]> SALOME platform Git repositories - modules/shaper.git/blob - src/PartSet/PartSet_Module.cpp
Salome HOME
Issue #2027 Sketcher Trim Feature
[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_WidgetFeaturePointSelector.h"
15 #include "PartSet_WidgetEditor.h"
16 #include "PartSet_WidgetFileSelector.h"
17 #include "PartSet_WidgetSketchCreator.h"
18 #include "PartSet_SketcherMgr.h"
19 #include "PartSet_SketcherReetntrantMgr.h"
20 #include "PartSet_ResultSketchPrs.h"
21 #include "PartSet_MenuMgr.h"
22 #include "PartSet_CustomPrs.h"
23 #include "PartSet_IconFactory.h"
24 #include "PartSet_WidgetChoice.h"
25 #include "PartSet_OverconstraintListener.h"
26
27 #include "PartSet_Filters.h"
28 #include "PartSet_FilterInfinite.h"
29
30 #include <PartSetPlugin_Remove.h>
31 #include <PartSetPlugin_Part.h>
32 #include <PartSetPlugin_Duplicate.h>
33
34 #include <ModuleBase_Operation.h>
35 #include <ModuleBase_OperationAction.h>
36 #include <ModuleBase_IViewer.h>
37 #include <ModuleBase_IViewWindow.h>
38 #include <ModuleBase_IPropertyPanel.h>
39 #include <ModuleBase_WidgetEditor.h>
40 #include <ModuleBase_WidgetValidated.h>
41 #include <ModuleBase_Tools.h>
42 #include <ModuleBase_OperationFeature.h>
43 #include <ModuleBase_WidgetFactory.h>
44 #include <ModuleBase_OperationDescription.h>
45 #include <ModuleBase_ViewerPrs.h>
46
47 #include <ModelAPI_Object.h>
48 #include <ModelAPI_Events.h>
49 #include <ModelAPI_Validator.h>
50 #include <ModelAPI_Data.h>
51 #include <ModelAPI_Session.h>
52 #include <ModelAPI_ResultBody.h>
53 #include <ModelAPI_AttributeString.h>
54 #include <ModelAPI_AttributeSelectionList.h>
55 #include <ModelAPI_Tools.h>
56 #include <ModelAPI_ResultConstruction.h>
57
58 #include <GeomDataAPI_Point2D.h>
59 #include <GeomDataAPI_Point.h>
60 #include <GeomDataAPI_Dir.h>
61
62 #include <XGUI_Displayer.h>
63 #include <XGUI_Workshop.h>
64 #include <XGUI_OperationMgr.h>
65 #include <XGUI_PropertyPanel.h>
66 #include <XGUI_ModuleConnector.h>
67 #include <XGUI_ContextMenuMgr.h>
68 #include <XGUI_Tools.h>
69 #include <XGUI_ObjectsBrowser.h>
70 #include <XGUI_SelectionMgr.h>
71 #include <XGUI_DataModel.h>
72 #include <XGUI_ErrorMgr.h>
73 #include <XGUI_CustomPrs.h>
74 #include <XGUI_SelectionMgr.h>
75 #include <XGUI_ActionsMgr.h>
76
77 #include <SketchPlugin_Feature.h>
78 #include <SketchPlugin_Sketch.h>
79 #include <SketchPlugin_ConstraintAngle.h>
80 #include <SketchPlugin_ConstraintLength.h>
81 #include <SketchPlugin_ConstraintDistance.h>
82 #include <SketchPlugin_ConstraintParallel.h>
83 #include <SketchPlugin_ConstraintPerpendicular.h>
84 #include <SketchPlugin_ConstraintRadius.h>
85
86 #include <SketcherPrs_SymbolPrs.h>
87 #include <SketcherPrs_Coincident.h>
88 #include <SketcherPrs_Tools.h>
89
90 #include <Events_Loop.h>
91 #include <Config_PropManager.h>
92 #include <Config_Keywords.h>
93
94 #include <AIS_Dimension.hxx>
95 #include <AIS_InteractiveObject.hxx>
96 #include <StdSelect_TypeOfFace.hxx>
97 #include <TopoDS_Vertex.hxx>
98 #include <TopoDS.hxx>
99 #include <TopoDS_Shape.hxx>
100 #include <BRep_Tool.hxx>
101
102 #include <QObject>
103 #include <QMouseEvent>
104 #include <QString>
105 #include <QTimer>
106 #include <QApplication>
107 #include <QMessageBox>
108 #include <QMainWindow>
109 #include <QLineEdit>
110 #include <QString>
111
112 #include <GeomAlgoAPI_FaceBuilder.h>
113 #include <GeomDataAPI_Dir.h>
114
115 #include <SelectMgr_ListIteratorOfListOfFilter.hxx>
116
117 #ifdef _DEBUG
118 #include <QDebug>
119 #endif
120
121 /*!Create and return new instance of XGUI_Module*/
122 extern "C" PARTSET_EXPORT ModuleBase_IModule* createModule(ModuleBase_IWorkshop* theWshop)
123 {
124   return new PartSet_Module(theWshop);
125 }
126
127 PartSet_Module::PartSet_Module(ModuleBase_IWorkshop* theWshop)
128 : ModuleBase_IModule(theWshop),
129   myVisualLayerId(0),
130   myIsOperationIsLaunched(false)
131 {
132   new PartSet_IconFactory();
133
134   mySketchMgr = new PartSet_SketcherMgr(this);
135   mySketchReentrantMgr = new PartSet_SketcherReetntrantMgr(theWshop);
136
137   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWshop);
138   XGUI_Workshop* aWorkshop = aConnector->workshop();
139
140   ModuleBase_IViewer* aViewer = theWshop->viewer();
141   connect(aViewer, SIGNAL(keyRelease(ModuleBase_IViewWindow*, QKeyEvent*)),
142           this, SLOT(onKeyRelease(ModuleBase_IViewWindow*, QKeyEvent*)));
143   connect(aViewer, SIGNAL(viewTransformed(int)),
144           SLOT(onViewTransformed(int)));
145   connect(aViewer, SIGNAL(viewCreated(ModuleBase_IViewWindow*)),
146           SLOT(onViewCreated(ModuleBase_IViewWindow*)));
147   myMenuMgr = new PartSet_MenuMgr(this);
148   myCustomPrs = new PartSet_CustomPrs(theWshop);
149
150   myOverconstraintListener = new PartSet_OverconstraintListener(theWshop);
151
152   Events_Loop* aLoop = Events_Loop::loop();
153   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_DOCUMENT_CHANGED));
154
155   mySelectionFilters.Append(new PartSet_GlobalFilter(myWorkshop));
156   mySelectionFilters.Append(new PartSet_FilterInfinite(myWorkshop));
157
158   setDefaultConstraintShown();
159
160   Config_PropManager::registerProp("Visualization", "operation_parameter_color",
161                           "Reference shape wireframe color in operation", Config_Prop::Color,
162                           PartSet_CustomPrs::OPERATION_PARAMETER_COLOR());
163   Config_PropManager::registerProp("Visualization", "operation_result_color",
164                           "Result shape wireframe color in operation", Config_Prop::Color,
165                           PartSet_CustomPrs::OPERATION_RESULT_COLOR());
166   Config_PropManager::registerProp("Visualization", "operation_highlight_color",
167                           "Multi selector item color in operation", Config_Prop::Color,
168                           PartSet_CustomPrs::OPERATION_HIGHLIGHT_COLOR());
169 }
170
171 PartSet_Module::~PartSet_Module()
172 {
173   SelectMgr_ListIteratorOfListOfFilter aIt(mySelectionFilters);
174   for (; aIt.More(); aIt.Next()) {
175     Handle(SelectMgr_Filter) aFilter = aIt.Value();
176     if (!aFilter.IsNull())
177       aFilter.Nullify();
178   }
179   delete myCustomPrs;
180   delete myOverconstraintListener;
181 }
182
183 void PartSet_Module::activateSelectionFilters()
184 {
185   SelectMgr_ListIteratorOfListOfFilter aIt(mySelectionFilters);
186   for (; aIt.More(); aIt.Next()) {
187     Handle(SelectMgr_Filter) aFilter = aIt.Value();
188     if (!aFilter.IsNull())
189       myWorkshop->viewer()->addSelectionFilter(aFilter);
190   }
191 }
192
193 void PartSet_Module::deactivateSelectionFilters()
194 {
195   SelectMgr_ListIteratorOfListOfFilter aIt(mySelectionFilters);
196   for (; aIt.More(); aIt.Next()) {
197     Handle(SelectMgr_Filter) aFilter = aIt.Value();
198     if (!aFilter.IsNull())
199       myWorkshop->viewer()->removeSelectionFilter(aFilter);
200   }
201 }
202
203 void PartSet_Module::storeSelection()
204 {
205   sketchMgr()->storeSelection();
206 }
207
208 void PartSet_Module::restoreSelection()
209 {
210   sketchMgr()->restoreSelection();
211 }
212
213 void PartSet_Module::registerValidators()
214 {
215   //Registering of validators
216   SessionPtr aMgr = ModelAPI_Session::get();
217   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
218   aFactory->registerValidator("PartSet_DistanceSelection", new PartSet_DistanceSelection);
219   aFactory->registerValidator("PartSet_LengthSelection", new PartSet_LengthSelection);
220   aFactory->registerValidator("PartSet_PerpendicularSelection", new PartSet_PerpendicularSelection);
221   aFactory->registerValidator("PartSet_ParallelSelection", new PartSet_ParallelSelection);
222   aFactory->registerValidator("PartSet_RadiusSelection", new PartSet_RadiusSelection);
223   aFactory->registerValidator("PartSet_RigidSelection", new PartSet_RigidSelection);
224   aFactory->registerValidator("PartSet_CoincidentSelection", new PartSet_CoincidentSelection);
225   aFactory->registerValidator("PartSet_HVDirSelection", new PartSet_HVDirSelection);
226   aFactory->registerValidator("PartSet_TangentSelection", new PartSet_TangentSelection);
227   aFactory->registerValidator("PartSet_FilletSelection", new PartSet_FilletSelection);
228   aFactory->registerValidator("PartSet_AngleSelection", new PartSet_AngleSelection);
229   aFactory->registerValidator("PartSet_EqualSelection", new PartSet_EqualSelection);
230   aFactory->registerValidator("PartSet_CollinearSelection", new PartSet_CollinearSelection);
231   aFactory->registerValidator("PartSet_MiddlePointSelection", new PartSet_MiddlePointSelection);
232   aFactory->registerValidator("PartSet_DifferentObjects", new PartSet_DifferentObjectsValidator);
233   aFactory->registerValidator("PartSet_CoincidentAttr", new PartSet_CoincidentAttr);
234   aFactory->registerValidator("PartSet_MultyTranslationSelection",
235     new PartSet_MultyTranslationSelection);
236   aFactory->registerValidator("PartSet_SplitSelection", new PartSet_SplitSelection);
237   aFactory->registerValidator("PartSet_ProjectionSelection", new PartSet_ProjectionSelection);
238 }
239
240 void PartSet_Module::registerProperties()
241 {
242   Config_PropManager::registerProp(SKETCH_TAB_NAME, "planes_size", "Size", Config_Prop::Double,
243                                    PLANE_SIZE);
244   Config_PropManager::registerProp(SKETCH_TAB_NAME, "planes_thickness", "Thickness",
245                                    Config_Prop::Integer, SKETCH_WIDTH);
246   Config_PropManager::registerProp(SKETCH_TAB_NAME, "rotate_to_plane",
247     "Rotate to plane when selected", Config_Prop::Boolean, "false");
248 }
249
250 void PartSet_Module::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget,
251                                             const bool isToConnect)
252 {
253   mySketchMgr->connectToPropertyPanel(theWidget, isToConnect);
254 }
255
256 void PartSet_Module::operationCommitted(ModuleBase_Operation* theOperation)
257 {
258   if (sketchMgr()->isNestedSketchOperation(theOperation)) {
259     mySketchMgr->commitNestedSketch(theOperation);
260   }
261
262   /// Restart sketcher operations automatically
263   if (!mySketchReentrantMgr->operationCommitted(theOperation)) {
264
265     ModuleBase_OperationFeature* aFOperation =
266       dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
267     if (aFOperation && !aFOperation->isEditOperation()) {
268       // the selection is cleared after commit the create operation
269       // in order to do not use the same selected objects in the restarted operation
270       // for common behaviour, the selection is cleared even if the operation is not restarted
271       getWorkshop()->selector()->clearSelection();
272     }
273   }
274 }
275
276 void PartSet_Module::operationAborted(ModuleBase_Operation* theOperation)
277 {
278   /// Restart sketcher operations automatically
279   mySketchReentrantMgr->operationAborted(theOperation);
280 }
281
282 void PartSet_Module::operationStarted(ModuleBase_Operation* theOperation)
283 {
284   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
285                                                                                 (theOperation);
286   if (aFOperation) {
287     XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(workshop());
288     XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
289
290     ModuleBase_ModelWidget* aFilledWidget = 0;
291     bool aPostonedWidgetActivation = false;
292
293     FeaturePtr aFeature = aFOperation->feature();
294     /// Restart sketcher operations automatically
295     /// it is important to call method of sketch reentrant manager before filling of PP
296     /// because it fills some created feature attributes, these new values should be used
297     /// to fill the property panel
298     mySketchReentrantMgr->operationStarted(theOperation);
299
300     aWorkshop->fillPropertyPanel(aFOperation);
301     // filling the operation values by the current selection
302     // if the operation can be committed after the controls filling, the method perform should
303     // be stopped. Otherwise unnecessary presentations can be shown(e.g. operation prs in sketch)
304     bool isOperationCommitted = false;
305     if (!aFOperation->isEditOperation()) {
306       std::string aGreedAttributeId = ModuleBase_Tools::findGreedAttribute(workshop(), aFeature);
307       // if there is a greed attribute, automatic commit by preselection
308       // for this feature is prohibited
309       aFilledWidget = aFOperation->activateByPreselection(aGreedAttributeId);
310       if (currentOperation() != aFOperation)
311         isOperationCommitted = true;
312       else {
313         if (aGreedAttributeId.empty()) {
314           // a signal should be emitted before the next widget activation
315           // because, the activation of the next widget will give a focus to the widget.
316           // As a result the value of the widget is initialized.
317           // And commit may happens until the value is entered.
318           if (aFilledWidget) {
319             if (mySketchReentrantMgr->canBeCommittedByPreselection())
320               isOperationCommitted = mySketchMgr->operationActivatedByPreselection();
321             // activate the next obligatory widget
322             if (!isOperationCommitted)
323               aPropertyPanel->activateNextWidget(aFilledWidget);
324           }
325         }
326         else { // there is a greed widget
327           const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
328           std::string aFirstAttributeId = aWidgets.front()->attributeID();
329           // activate next widget after greeded if it is the first widget in the panel
330           // else the first panel widget is already activated by operation start
331           if (aFirstAttributeId == aGreedAttributeId)
332             aPostonedWidgetActivation = true;
333         }
334       }
335     } if (!isOperationCommitted) {
336       aWorkshop->connectToPropertyPanel(true);
337       updateSketcherOnStart(aFOperation);
338       updatePresentationsOnStart(aFOperation);
339
340       // the objects of the current operation should be deactivated
341       QObjectPtrList anObjects;
342       anObjects.append(aFeature);
343       std::list<ResultPtr> aResults;
344       ModelAPI_Tools::allResults(aFeature, aResults);
345       std::list<ResultPtr>::const_iterator aIt;
346       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
347         anObjects.append(*aIt);
348       }
349       QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
350       for (; anIt != aLast; anIt++)
351         aWorkshop->deactivateActiveObject(*anIt, false);
352       if (anObjects.size() > 0) {
353         XGUI_Displayer* aDisplayer = aWorkshop->displayer();
354         aDisplayer->updateViewer();
355       }
356       /// state of command actions should be updated after displayed objects modification because
357       /// deactivation(for example) of objects may influence on selection in the viewer
358       /// State of command actions may depend on selection in the viewer(e.g. Sketch)
359       workshop()->updateCommandStatus();
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 == "sketch_feature_point_selector") {
749     PartSet_WidgetFeaturePointSelector* aPointSelectorWgt =
750                           new PartSet_WidgetFeaturePointSelector(theParent, aWorkshop, theWidgetApi);
751     aPointSelectorWgt->setSketcher(mySketchMgr->activeSketch());
752     aWgt = aPointSelectorWgt;
753   }
754   else if (theType == WDG_DOUBLEVALUE_EDITOR) {
755     aWgt = new PartSet_WidgetEditor(theParent, aWorkshop, theWidgetApi);
756   } else if (theType == "export_file_selector") {
757     aWgt = new PartSet_WidgetFileSelector(theParent, aWorkshop, theWidgetApi);
758   } else if (theType == "sketch_launcher") {
759     aWgt = new PartSet_WidgetSketchCreator(theParent, this, theWidgetApi);
760   } else if (theType == "module_choice") {
761     aWgt = new PartSet_WidgetChoice(theParent, theWidgetApi);
762     connect(aWgt, SIGNAL(itemSelected(ModuleBase_ModelWidget*, int)),
763             this, SLOT(onChoiceChanged(ModuleBase_ModelWidget*, int)));
764   }
765   return aWgt;
766 }
767
768 ModuleBase_ModelWidget* PartSet_Module::activeWidget() const
769 {
770   ModuleBase_ModelWidget* anActiveWidget = 0;
771
772   anActiveWidget = mySketchReentrantMgr->internalActiveWidget();
773   if (!anActiveWidget) {
774     ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
775     if (aOperation) {
776       ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
777       anActiveWidget = aPanel ? aPanel->activeWidget() : 0;
778     }
779   }
780   return anActiveWidget;
781 }
782
783 bool PartSet_Module::deleteObjects()
784 {
785   bool isProcessed = false;
786
787   XGUI_Workshop* aWorkshop = getWorkshop();
788   XGUI_OperationMgr* anOpMgr = aWorkshop->operationMgr();
789
790   //SessionPtr aMgr = ModelAPI_Session::get();
791   // 1. check whether the delete should be processed in the module
792   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
793   bool isSketchOp = PartSet_SketcherMgr::isSketchOperation(anOperation),
794        isNestedOp = sketchMgr()->isNestedSketchOperation(anOperation);
795   if (isSketchOp || isNestedOp) {
796     isProcessed = true;
797     // 2. find selected presentations
798     // selected objects should be collected before the current operation abort because
799     // the abort leads to selection lost on constraint objects. It can be corrected after #386 issue
800     ModuleBase_ISelection* aSel = workshop()->selection();
801     QObjectPtrList aSelectedObj = aSel->selectedPresentations();
802     // if there are no selected objects in the viewer, that means that the selection in another
803     // place cased this method. It is necessary to return the false value to understande in above
804     // method that delete is not processed
805     if (aSelectedObj.count() == 0)
806       return false;
807
808     // avoid delete of the objects, which are not belong to the current sketch
809     // in order to do not delete results of other sketches
810     QObjectPtrList aSketchObjects;
811     QObjectPtrList::const_iterator anIt = aSelectedObj.begin(), aLast = aSelectedObj.end();
812     for ( ; anIt != aLast; anIt++) {
813       ObjectPtr anObject = *anIt;
814       if (mySketchMgr->isObjectOfSketch(anObject)) {
815         // sketch feature should be used in this list because workshop deletes features only
816         // results are skipped
817         FeaturePtr aSketchFeature = ModelAPI_Feature::feature(anObject);
818         aSketchObjects.append(aSketchFeature);
819       }
820     }
821     // if the selection contains only local selected presentations from other sketches,
822     // the Delete operation should not be done at all
823     if (aSketchObjects.size() == 0)
824       return true;
825
826     // 3. start operation
827     QString aDescription = aWorkshop->contextMenuMgr()->action("DELETE_CMD")->text();
828     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, this);
829
830     // the active nested sketch operation should be aborted unconditionally
831     // the Delete action should be additionally granted for the Sketch operation
832     // in order to do not abort/commit it
833     if (!anOpMgr->canStartOperation(anOpAction->id()))
834       return true; // the objects are processed but can not be deleted
835
836     anOpMgr->startOperation(anOpAction);
837
838     // WORKAROUND, should be done to avoid viewer highlight update after deletetion of objects
839     // the problem is in AIS Dimensions recompute
840     // if a line and the dim are removed, line is the first
841     // it causes the AIS recompute, where the base line is null,
842     // the result is empty AIS in the viewer
843     XGUI_Tools::workshop(myWorkshop)->selector()->clearSelection();
844
845     // 4. delete features
846     // sketch feature should be skipped, only sub-features can be removed
847     // when sketch operation is active
848     aWorkshop->deleteFeatures(aSketchObjects);
849     // 5. stop operation
850     anOpMgr->commitOperation();
851   }
852   return isProcessed;
853 }
854
855 void PartSet_Module::onFeatureTriggered()
856 {
857   // is commented for imp: Unpressing the button of the current action must behave like
858   // a validation if the entity can be created (instead of Cancel, as currently)
859   /*QAction* aCmd = dynamic_cast<QAction*>(sender());
860   if (aCmd->isCheckable() && aCmd->isChecked()) {
861     // 1. check whether the delete should be processed in the module
862     ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
863     bool isNestedOp = myModule->sketchMgr()->isNestedCreateOperation(anOperation);
864     if (isNestedOp) {
865       // in case if in the viewer nothing is displayed, the create operation should not be
866       // comitted even if all values of the feature are initialized
867       if (!mySketchMgr->canDisplayCurrentCreatedFeature()) {
868         // the action information should be saved before the operation is aborted
869         // because this abort leads to update command status, which unchecks this action
870         anOperation->abort();
871         launchOperation(aCmd->data().toString());
872       }
873     }
874   }*/
875   ModuleBase_IModule::onFeatureTriggered();
876 }
877
878 void PartSet_Module::editFeature(FeaturePtr theFeature)
879 {
880   storeConstraintsState(theFeature->getKind());
881   ModuleBase_IModule::editFeature(theFeature);
882 }
883
884 bool PartSet_Module::canCommitOperation() const
885 {
886   return true;
887 }
888
889 void PartSet_Module::launchOperation(const QString& theCmdId)
890 {
891   myIsOperationIsLaunched = true;
892   storeConstraintsState(theCmdId.toStdString());
893   updateConstraintsState(theCmdId.toStdString());
894
895   ModuleBase_IModule::launchOperation(theCmdId);
896
897   myIsOperationIsLaunched = false;
898 }
899
900 void PartSet_Module::storeConstraintsState(const std::string& theFeatureKind)
901 {
902   if (myWorkshop->currentOperation() &&
903       myWorkshop->currentOperation()->id().toStdString() == SketchPlugin_Sketch::ID()) {
904     const QMap<PartSet_Tools::ConstraintVisibleState, bool>& aShownStates =
905                                                   mySketchMgr->showConstraintStates();
906     myHasConstraintShown = aShownStates;
907   }
908 }
909
910 void PartSet_Module::updateConstraintsState(const std::string& theFeatureKind)
911 {
912   if (PartSet_SketcherMgr::constraintsIdList().contains(theFeatureKind.c_str()) ||
913       PartSet_SketcherMgr::replicationsIdList().contains(theFeatureKind.c_str())) {
914     // Show constraints if a constraint was anOperation
915     mySketchMgr->updateBySketchParameters(PartSet_Tools::Geometrical, true);
916     mySketchMgr->updateBySketchParameters(PartSet_Tools::Dimensional, true);
917     mySketchMgr->updateBySketchParameters(PartSet_Tools::Expressions,
918                                           myHasConstraintShown[PartSet_Tools::Expressions]);
919   }
920 }
921
922 void PartSet_Module::onObjectDisplayed(ObjectPtr theObject, AISObjectPtr theAIS)
923 {
924   Handle(AIS_InteractiveObject) anAIS = theAIS->impl<Handle(AIS_InteractiveObject)>();
925   if (!anAIS.IsNull()) {
926     Handle(AIS_InteractiveContext) aCtx = anAIS->GetContext();
927     Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(anAIS);
928     if (!aDim.IsNull()) {
929       aCtx->SetZLayer(aDim, myVisualLayerId);
930     } else {
931       Handle(SketcherPrs_SymbolPrs) aCons = Handle(SketcherPrs_SymbolPrs)::DownCast(anAIS);
932       if (!aCons.IsNull())
933         aCtx->SetZLayer(aCons, myVisualLayerId);
934     }
935   }
936 }
937
938 void PartSet_Module::onBeforeObjectErase(ObjectPtr theObject, AISObjectPtr theAIS)
939 {
940   // this is obsolete
941   // it should be recomputed in order to disappear in the viewer if the corresponded object
942   // is erased
943   //if (myCustomPrs->isActive())
944   //  myCustomPrs->redisplay(theObject, false);
945 }
946
947 void PartSet_Module::onViewTransformed(int theTrsfType)
948 {
949   // Set length of arrows constant in pixel size
950   // if the operation is panning or rotate or panglobal then do nothing
951   if ((theTrsfType == 1) || (theTrsfType == 3) || (theTrsfType == 4))
952     return;
953   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
954   Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
955   if (aContext.IsNull())
956     return;
957
958   //Handle(V3d_View) aView = aViewer->activeView();
959
960   XGUI_Workshop* aWorkshop = getWorkshop();
961   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
962   Handle(V3d_Viewer) aV3dViewer = aContext->CurrentViewer();
963   Handle(V3d_View) aView;
964   double aScale = 0;
965   for (aV3dViewer->InitDefinedViews();
966        aV3dViewer->MoreDefinedViews();
967        aV3dViewer->NextDefinedViews()) {
968     Handle(V3d_View) aV = aV3dViewer->DefinedView();
969     double aS = aV->Scale();
970     if (aS > aScale) {
971       aScale = aS;
972       aView = aV;
973     }
974   }
975   if (aView.IsNull())
976     return;
977   double aLen = aView->Convert(SketcherPrs_Tools::getDefaultArrowSize());
978
979   double aPrevLen = SketcherPrs_Tools::getArrowSize();
980   SketcherPrs_Tools::setArrowSize(aLen);
981   const double aPrevScale = aViewer->Scale(aViewer->activeView());
982   const double aCurScale = aViewer->activeView()->Camera()->Scale();
983   aViewer->SetScale(aViewer->activeView(), aCurScale);
984   SketcherPrs_Tools::setTextHeight (aCurScale / aPrevScale * SketcherPrs_Tools::getTextHeight());
985   bool isModified = false;
986   QList<AISObjectPtr> aPrsList = aDisplayer->displayedPresentations();
987   foreach (AISObjectPtr aAIS, aPrsList) {
988     Handle(AIS_InteractiveObject) aAisObj = aAIS->impl<Handle(AIS_InteractiveObject)>();
989
990     Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(aAisObj);
991     if (!aDim.IsNull()) {
992       aDim->DimensionAspect()->ArrowAspect()->SetLength(aLen);
993       aContext->Redisplay(aDim, false);
994       isModified = true;
995     }
996   }
997   if (isModified)
998     aDisplayer->updateViewer();
999 }
1000
1001 bool PartSet_Module::isCustomPrsActivated(const ModuleBase_CustomizeFlag& theFlag) const
1002 {
1003   return myCustomPrs->isActive(theFlag);
1004 }
1005
1006 void PartSet_Module::activateCustomPrs(const FeaturePtr& theFeature,
1007                                        const ModuleBase_CustomizeFlag& theFlag,
1008                                        const bool theUpdateViewer)
1009 {
1010   myCustomPrs->activate(theFeature, theFlag, theUpdateViewer);
1011 }
1012
1013 void PartSet_Module::deactivateCustomPrs(const ModuleBase_CustomizeFlag& theFlag,
1014                                          const bool theUpdateViewer)
1015 {
1016   myCustomPrs->deactivate(theFlag, theUpdateViewer);
1017 }
1018
1019 bool PartSet_Module::customisePresentation(ResultPtr theResult, AISObjectPtr thePrs,
1020                                            std::shared_ptr<GeomAPI_ICustomPrs> theCustomPrs)
1021 {
1022   bool aCustomized = false;
1023
1024   XGUI_Workshop* aWorkshop = getWorkshop();
1025   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1026   ObjectPtr anObject = aDisplayer->getObject(thePrs);
1027   if (!anObject)
1028     return aCustomized;
1029
1030   if (!theResult.get()) {
1031     bool isConflicting = myOverconstraintListener->isConflictingObject(anObject);
1032     // customize sketch symbol presentation
1033     if (thePrs.get()) {
1034       Handle(AIS_InteractiveObject) anAISIO = thePrs->impl<Handle(AIS_InteractiveObject)>();
1035       if (!anAISIO.IsNull()) {
1036         if (!Handle(SketcherPrs_SymbolPrs)::DownCast(anAISIO).IsNull()) {
1037           Handle(SketcherPrs_SymbolPrs) aPrs = Handle(SketcherPrs_SymbolPrs)::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         } else if (!Handle(SketcherPrs_Coincident)::DownCast(anAISIO).IsNull()) {
1045           Handle(SketcherPrs_Coincident) aPrs = Handle(SketcherPrs_Coincident)::DownCast(anAISIO);
1046           if (!aPrs.IsNull()) {
1047             std::vector<int> aColor;
1048             myOverconstraintListener->getConflictingColor(aColor);
1049             aPrs->SetConflictingConstraint(isConflicting, aColor);
1050             aCustomized = true;
1051           }
1052         }
1053       }
1054     }
1055     // customize sketch dimension constraint presentation
1056     if (!aCustomized) {
1057       std::vector<int> aColor;
1058       if (isConflicting) {
1059         myOverconstraintListener->getConflictingColor(aColor);
1060       }
1061       if (aColor.empty())
1062         XGUI_CustomPrs::getDefaultColor(anObject, true, aColor);
1063       if (!aColor.empty()) {
1064         aCustomized = thePrs->setColor(aColor[0], aColor[1], aColor[2]);
1065       }
1066     }
1067   }
1068   // customize dimentional constrains
1069   sketchMgr()->customizePresentation(anObject);
1070
1071   return aCustomized;
1072 }
1073
1074 bool PartSet_Module::customizeObject(ObjectPtr theObject, const ModuleBase_CustomizeFlag& theFlag,
1075                                      const bool theUpdateViewer)
1076 {
1077   bool isRedisplayed = false;
1078   if (myCustomPrs->isActive(theFlag))
1079     isRedisplayed = myCustomPrs->redisplay(theObject, theFlag, theUpdateViewer);
1080
1081   return isRedisplayed;
1082 }
1083
1084 void PartSet_Module::customizeObjectBrowser(QWidget* theObjectBrowser)
1085 {
1086   XGUI_ObjectsBrowser* aOB = dynamic_cast<XGUI_ObjectsBrowser*>(theObjectBrowser);
1087   if (aOB) {
1088     QLabel* aLabel = aOB->activeDocLabel();
1089     aLabel->installEventFilter(myMenuMgr);
1090     connect(aLabel, SIGNAL(customContextMenuRequested(const QPoint&)),
1091           SLOT(onActiveDocPopup(const QPoint&)));
1092     aOB->treeView()->setExpandsOnDoubleClick(false);
1093     connect(aOB->treeView(), SIGNAL(doubleClicked(const QModelIndex&)),
1094       SLOT(onTreeViewDoubleClick(const QModelIndex&)));
1095
1096     Events_Loop* aLoop = Events_Loop::loop();
1097     aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1098   }
1099 }
1100
1101 void PartSet_Module::onActiveDocPopup(const QPoint& thePnt)
1102 {
1103   SessionPtr aMgr = ModelAPI_Session::get();
1104   QAction* aActivatePartAction = myMenuMgr->action("ACTIVATE_PARTSET_CMD");
1105
1106   XGUI_Workshop* aWorkshop = getWorkshop();
1107   QLabel* aHeader = aWorkshop->objectBrowser()->activeDocLabel();
1108
1109   aActivatePartAction->setEnabled((aMgr->activeDocument() != aMgr->moduleDocument()));
1110
1111   QMenu aMenu;
1112   aMenu.addAction(aActivatePartAction);
1113   aMenu.exec(aHeader->mapToGlobal(thePnt));
1114 }
1115
1116 Handle(AIS_InteractiveObject) PartSet_Module::createPresentation(const ResultPtr& theResult)
1117 {
1118   return mySketchMgr->createPresentation(theResult);
1119 }
1120
1121
1122 ObjectPtr PartSet_Module::findPresentedObject(const AISObjectPtr& theAIS) const
1123 {
1124   ObjectPtr anObject;
1125   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1126   if (aOperation) {
1127     /// If last line finished on vertex the lines creation sequence has to be break
1128     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
1129     if (aPanel) {
1130       ModuleBase_ModelWidget* anActiveWidget = aPanel->activeWidget();
1131       // if there is an active widget, find the presented object in it
1132       if (!anActiveWidget)
1133         anActiveWidget = aPanel->preselectionWidget();
1134
1135       ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
1136                                                                              (anActiveWidget);
1137       if (aWidgetValidated)
1138         anObject = aWidgetValidated->findPresentedObject(theAIS);
1139     }
1140   }
1141   return anObject;
1142 }
1143
1144 bool PartSet_Module::canBeShaded(Handle(AIS_InteractiveObject) theAIS) const
1145 {
1146   bool aCanBeShaged = true;
1147
1148   Handle(PartSet_ResultSketchPrs) aPrs = Handle(PartSet_ResultSketchPrs)::DownCast(theAIS);
1149   if (!aPrs.IsNull())
1150     aCanBeShaged = false;
1151
1152   return aCanBeShaged;
1153 }
1154
1155 void PartSet_Module::addObjectBrowserMenu(QMenu* theMenu) const
1156 {
1157   QObjectPtrList aObjects = myWorkshop->selection()->selectedObjects();
1158   int aSelected = aObjects.size();
1159   SessionPtr aMgr = ModelAPI_Session::get();
1160   QAction* aActivatePartAction = myMenuMgr->action("ACTIVATE_PART_CMD");
1161
1162   ModuleBase_Operation* aCurrentOp = myWorkshop->currentOperation();
1163   if (aSelected == 1) {
1164     bool hasResult = false;
1165     bool hasFeature = false;
1166     bool hasParameter = false;
1167     bool hasCompositeOwner = false;
1168     ModuleBase_Tools::checkObjects(aObjects, hasResult, hasFeature, hasParameter,
1169                                    hasCompositeOwner);
1170     ObjectPtr aObject = aObjects.first();
1171     if (aObject) {
1172       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1173       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1174       bool isPart = aPart.get() ||
1175         (aFeature.get() && (aFeature->getKind() == PartSetPlugin_Part::ID()));
1176       if (isPart) {
1177         DocumentPtr aPartDoc;
1178         if (!aPart.get()) {
1179           aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFeature->firstResult());
1180         }
1181         if (aPart.get()) // this may be null is Part feature is disabled
1182           aPartDoc = aPart->partDoc();
1183
1184         theMenu->addAction(aActivatePartAction);
1185         aActivatePartAction->setEnabled((aMgr->activeDocument() != aPartDoc));
1186
1187       } else if (aObject->document() == aMgr->activeDocument()) {
1188         if (hasParameter || hasFeature) {
1189           myMenuMgr->action("EDIT_CMD")->setEnabled(true);
1190           theMenu->addAction(myMenuMgr->action("EDIT_CMD"));
1191           if (aCurrentOp && aFeature.get()) {
1192             if (aCurrentOp->id().toStdString() == aFeature->getKind())
1193               myMenuMgr->action("EDIT_CMD")->setEnabled(false);
1194           }
1195         }
1196       }
1197     }
1198   }
1199   bool aNotDeactivate = (aCurrentOp == 0);
1200   if (!aNotDeactivate) {
1201     aActivatePartAction->setEnabled(false);
1202   }
1203 }
1204
1205 #define EXPAND_PARENT(OBJ) \
1206 QModelIndex aObjIndex = aDataModel->objectIndex(OBJ); \
1207 if (aObjIndex.isValid()) { \
1208   QModelIndex aParent = aObjIndex.parent(); \
1209   int aCount = aDataModel->rowCount(aParent); \
1210   if (aCount == 1) \
1211     aTreeView->setExpanded(aParent, true); \
1212 }
1213
1214
1215 void PartSet_Module::processEvent(const std::shared_ptr<Events_Message>& theMessage)
1216 {
1217   if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_DOCUMENT_CHANGED)) {
1218     // Do not change activation of parts if an operation active
1219     static QStringList aAllowActivationList;
1220     if (aAllowActivationList.isEmpty())
1221       aAllowActivationList <<
1222       QString(PartSetPlugin_Part::ID().c_str()) <<
1223       QString(PartSetPlugin_Duplicate::ID().c_str()) <<
1224       QString(PartSetPlugin_Remove::ID().c_str());
1225     if (myWorkshop->currentOperation() &&
1226       (!aAllowActivationList.contains(myWorkshop->currentOperation()->id())))
1227       return;
1228     XGUI_Workshop* aWorkshop = getWorkshop();
1229     XGUI_DataTree* aTreeView = aWorkshop->objectBrowser()->treeView();
1230     QLabel* aLabel = aWorkshop->objectBrowser()->activeDocLabel();
1231     QPalette aPalet = aLabel->palette();
1232
1233     SessionPtr aMgr = ModelAPI_Session::get();
1234     DocumentPtr aActiveDoc = aMgr->activeDocument();
1235     if (myActivePartIndex.isValid())
1236       aTreeView->setExpanded(myActivePartIndex, false);
1237     XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1238     myActivePartIndex = aDataModel->documentRootIndex(aActiveDoc);
1239     if (myActivePartIndex.isValid())
1240       aTreeView->setExpanded(myActivePartIndex, true);
1241
1242     aLabel->setPalette(aPalet);
1243     aWorkshop->updateCommandStatus();
1244
1245     // Update displayed objects in order to update active color
1246     XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1247     QObjectPtrList aObjects = aDisplayer->displayedObjects();
1248     bool aHidden;
1249     foreach(ObjectPtr aObj, aObjects) {
1250       aHidden = !aObj->data() || !aObj->data()->isValid() ||
1251         aObj->isDisabled() || (!aObj->isDisplayed());
1252       if (!aHidden)
1253         aDisplayer->redisplay(aObj, false);
1254     }
1255     aDisplayer->updateViewer();
1256   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
1257     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
1258         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
1259     std::set<ObjectPtr> aObjects = aUpdMsg->objects();
1260
1261     ObjectPtr aConstrObj;
1262     ObjectPtr aResultObj;
1263     std::set<ObjectPtr>::const_iterator aIt;
1264     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
1265     for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
1266       ObjectPtr aObject = (*aIt);
1267       if ((!aResultObj.get()) && (aObject->groupName() == ModelAPI_ResultBody::group())
1268           && (aObject->document() != aRootDoc))
1269         aResultObj = aObject;
1270       if ((!aConstrObj.get()) && (aObject->groupName() == ModelAPI_ResultConstruction::group())
1271           && (aObject->document() != aRootDoc))
1272         aConstrObj = aObject;
1273       if (aResultObj.get() && aConstrObj.get())
1274         break;
1275     }
1276
1277     if (aResultObj.get() || aConstrObj.get()) {
1278       XGUI_Workshop* aWorkshop = getWorkshop();
1279       XGUI_DataTree* aTreeView = aWorkshop->objectBrowser()->treeView();
1280       XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1281
1282       if (aResultObj.get()) {
1283         EXPAND_PARENT(aResultObj)
1284       }
1285       if (aConstrObj.get()) {
1286         EXPAND_PARENT(aConstrObj)
1287       }
1288     }
1289   }
1290 }
1291
1292 void PartSet_Module::onTreeViewDoubleClick(const QModelIndex& theIndex)
1293 {
1294   if (myWorkshop->currentOperation()) // Do not change activation of parts if an operation active
1295     return;
1296   SessionPtr aMgr = ModelAPI_Session::get();
1297   if (!theIndex.isValid()) {
1298     // It seems that this code is obsolete
1299     //aMgr->setActiveDocument(aMgr->moduleDocument());
1300     return;
1301   }
1302   if (theIndex.column() != 0) // Use only first column
1303     return;
1304
1305   XGUI_Workshop* aWorkshop = getWorkshop();
1306   XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1307   // De not use non editable Indexes
1308   if ((aDataModel->flags(theIndex) & Qt::ItemIsSelectable) == 0)
1309     return;
1310   ObjectPtr aObj = aDataModel->object(theIndex);
1311
1312   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1313   if (!aPart.get()) { // Probably this is Feature
1314     FeaturePtr aPartFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
1315     if (aPartFeature.get() && (aPartFeature->getKind() == PartSetPlugin_Part::ID())) {
1316       aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aPartFeature->firstResult());
1317     }
1318   }
1319   if (aPart.get()) { // if this is a part
1320     if (aPart->partDoc() == aMgr->activeDocument()) {
1321       myMenuMgr->activatePartSet();
1322     } else {
1323       myMenuMgr->activatePart(aPart);
1324     }
1325   }
1326 }
1327
1328
1329 void PartSet_Module::onViewCreated(ModuleBase_IViewWindow*)
1330 {
1331   // z layer is created for all started operations in order to visualize operation AIS presentation
1332   // over the object
1333   Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
1334   if (aContext.IsNull())
1335     return;
1336
1337   Handle(V3d_Viewer) aViewer = aContext->CurrentViewer();
1338   if (myVisualLayerId == 0) {
1339     if (myVisualLayerId == 0)
1340       aViewer->AddZLayer(myVisualLayerId);
1341   } else {
1342     TColStd_SequenceOfInteger aZList;
1343     aViewer->GetAllZLayers(aZList);
1344     bool aFound = false;
1345     for (int i = 1; i <= aZList.Length(); i++) {
1346       if (aZList(i) == myVisualLayerId) {
1347         aFound = true;
1348         break;
1349       }
1350     }
1351     if (!aFound)
1352       aViewer->AddZLayer(myVisualLayerId);
1353   }
1354   // if there is an active operation with validated widget,
1355   // the filters of this widget should be activated in the created view
1356   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1357   if (aOperation) {
1358     ModuleBase_ModelWidget* anActiveWidget = activeWidget();
1359     if (anActiveWidget) {
1360       ModuleBase_WidgetSelector* aWSelector =
1361         dynamic_cast<ModuleBase_WidgetSelector*>(anActiveWidget);
1362       if (aWSelector)
1363         aWSelector->activateSelectionAndFilters(true);
1364     }
1365   }
1366 }
1367
1368 //******************************************************
1369 void PartSet_Module::widgetStateChanged(int thePreviousState)
1370 {
1371   mySketchMgr->widgetStateChanged(thePreviousState);
1372 }
1373
1374 bool PartSet_Module::processEnter(const std::string& thePreviousAttributeID)
1375 {
1376   return mySketchReentrantMgr->processEnter(thePreviousAttributeID);
1377 }
1378
1379 //******************************************************
1380 void PartSet_Module::beforeOperationStopped(ModuleBase_Operation* theOperation)
1381 {
1382   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
1383     mySketchMgr->stopSketch(theOperation);
1384   }
1385 }
1386
1387 //******************************************************
1388 GeomShapePtr PartSet_Module::findShape(const AttributePtr& theAttribute)
1389 {
1390   GeomShapePtr aGeomShape;
1391
1392   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
1393   if (anOperation && sketchMgr()->isNestedSketchOperation(anOperation)) {
1394     aGeomShape = PartSet_Tools::findShapeBy2DPoint(theAttribute, myWorkshop);
1395   }
1396   return aGeomShape;
1397 }
1398
1399 //******************************************************
1400 AttributePtr PartSet_Module::findAttribute(const ObjectPtr& theObject,
1401                                            const GeomShapePtr& theGeomShape)
1402 {
1403   AttributePtr anAttribute;
1404   GeomShapePtr aGeomShape = theGeomShape;
1405   if (!aGeomShape.get()) {
1406     // processing shape of result, e.g. sketch circle center is selected, this is a result
1407     // the geom shape is empty, the shape of result should be used
1408     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1409     if (aResult.get()) {
1410       aGeomShape = aResult->shape();
1411     }
1412   }
1413
1414   if (aGeomShape.get()) {
1415     TopoDS_Shape aTDSShape = aGeomShape->impl<TopoDS_Shape>();
1416     return PartSet_Tools::findAttributeBy2dPoint(theObject, aTDSShape,
1417                                                  mySketchMgr->activeSketch());
1418   }
1419   return anAttribute;
1420 }
1421
1422 //******************************************************
1423 void PartSet_Module::onChoiceChanged(ModuleBase_ModelWidget* theWidget,
1424                                      int theIndex)
1425 {
1426   PartSet_WidgetChoice* aChoiceWidget = dynamic_cast<PartSet_WidgetChoice*>(theWidget);
1427   if (!aChoiceWidget)
1428     return;
1429
1430   QString aChoiceTitle = aChoiceWidget->getPropertyPanelTitle(theIndex);
1431   if (!aChoiceTitle.isEmpty()) {
1432     ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1433     if (!aOperation)
1434       return;
1435     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
1436     if (aPanel)
1437       aPanel->setWindowTitle(aChoiceTitle);
1438   }
1439 }
1440
1441 //******************************************************
1442 XGUI_Workshop* PartSet_Module::getWorkshop() const
1443 {
1444   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
1445   return aConnector->workshop();
1446 }
1447
1448 //******************************************************
1449 void PartSet_Module::setDefaultConstraintShown()
1450 {
1451   myHasConstraintShown[PartSet_Tools::Geometrical] = true;
1452   myHasConstraintShown[PartSet_Tools::Dimensional] = true;
1453   myHasConstraintShown[PartSet_Tools::Expressions] = false;
1454 }