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