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