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