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