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