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