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