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