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