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