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