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