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