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