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