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