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