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