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