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