Salome HOME
164253ada2f9b80fcc2847e34355aa8127bd7002
[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::onViewTransformed(int theTrsfType)
713 {
714   // Set length of arrows constant in pixel size
715   // if the operation is panning or rotate or panglobal then do nothing
716   if ((theTrsfType == 1) || (theTrsfType == 3) || (theTrsfType == 4))
717     return;
718
719   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
720   //Handle(V3d_View) aView = aViewer->activeView();
721
722   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myWorkshop);
723   XGUI_Workshop* aWorkshop = aConnector->workshop();
724   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
725   Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
726
727   Handle(V3d_Viewer) aV3dViewer = aContext->CurrentViewer();
728   Handle(V3d_View) aView;
729   double aScale = 0;
730   for (aV3dViewer->InitDefinedViews(); 
731        aV3dViewer->MoreDefinedViews(); 
732        aV3dViewer->NextDefinedViews()) {
733     Handle(V3d_View) aV = aV3dViewer->DefinedView();
734     double aS = aV->Scale();
735     if (aS > aScale) {
736       aScale = aS;
737       aView = aV;
738     }
739   }
740   if (aView.IsNull())
741     return;
742   double aLen = aView->Convert(20);
743
744   double aPrevLen = SketcherPrs_Tools::getArrowSize();
745   SketcherPrs_Tools::setArrowSize(aLen);
746   const double aPrevScale = aViewer->Scale(aViewer->activeView());
747   const double aCurScale = aViewer->activeView()->Camera()->Scale();
748   aViewer->SetScale(aViewer->activeView(), aCurScale);
749   SketcherPrs_Tools::setTextHeight (aCurScale / aPrevScale * SketcherPrs_Tools::getTextHeight());
750   bool isModified = false;
751   QList<AISObjectPtr> aPrsList = aDisplayer->displayedPresentations();
752   foreach (AISObjectPtr aAIS, aPrsList) {
753     Handle(AIS_InteractiveObject) aAisObj = aAIS->impl<Handle(AIS_InteractiveObject)>();
754
755     Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(aAisObj);
756     if (!aDim.IsNull()) {
757       aDim->DimensionAspect()->ArrowAspect()->SetLength(aLen);
758       aContext->Redisplay(aDim, false);
759       isModified = true;
760     }
761   }
762   if (isModified)
763     aDisplayer->updateViewer();
764 }
765
766 void PartSet_Module::customizeObject(ObjectPtr theObject)
767 {
768   if (myCustomPrs->isActive())
769     myCustomPrs->customize(theObject);
770 }
771
772 void PartSet_Module::customizeObjectBrowser(QWidget* theObjectBrowser)
773 {
774   XGUI_ObjectsBrowser* aOB = dynamic_cast<XGUI_ObjectsBrowser*>(theObjectBrowser);
775   if (aOB) {
776     QLineEdit* aLabel = aOB->activeDocLabel();
777     QPalette aPalet = aLabel->palette();
778     aPalet.setColor(QPalette::Text, QColor(0, 72, 140));
779     aLabel->setPalette(aPalet);
780     aOB->treeView()->setExpandsOnDoubleClick(false);
781 #ifdef ModuleDataModel
782     connect(aOB->treeView(), SIGNAL(doubleClicked(const QModelIndex&)), 
783       SLOT(onTreeViewDoubleClick(const QModelIndex&)));
784     connect(aOB, SIGNAL(headerMouseDblClicked(const QModelIndex&)), 
785       SLOT(onTreeViewDoubleClick(const QModelIndex&)));
786     connect(aOB->treeView(), SIGNAL(doubleClicked(const QModelIndex&)), 
787       myDataModel, SLOT(onMouseDoubleClick(const QModelIndex&)));
788 #endif
789   }
790 }
791
792 ObjectPtr PartSet_Module::findPresentedObject(const AISObjectPtr& theAIS) const
793 {
794   ObjectPtr anObject;
795   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
796   if (aOperation) {
797     /// If last line finished on vertex the lines creation sequence has to be break
798     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
799     ModuleBase_ModelWidget* anActiveWidget = aPanel->activeWidget();
800     // if there is an active widget, find the presented object in it
801     if (!anActiveWidget)
802       anActiveWidget = aPanel->preselectionWidget();
803     
804     ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
805                                                                            (anActiveWidget);
806     if (aWidgetValidated)
807       anObject = aWidgetValidated->findPresentedObject(theAIS);
808   }
809   return anObject;
810 }
811
812 void PartSet_Module::addObjectBrowserMenu(QMenu* theMenu) const
813 {
814   QObjectPtrList aObjects = myWorkshop->selection()->selectedObjects();
815   int aSelected = aObjects.size();
816   SessionPtr aMgr = ModelAPI_Session::get();
817   if (aSelected == 1) {
818     bool hasResult = false;
819     bool hasFeature = false;
820     bool hasParameter = false;
821     bool hasSubFeature = false;
822     ModuleBase_Tools::checkObjects(aObjects, hasResult, hasFeature, hasParameter, hasSubFeature);
823
824     ObjectPtr aObject = aObjects.first();
825     if (aObject) {
826       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
827       FeaturePtr aPartFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
828       bool isPart = aPart.get() || 
829         (aPartFeature.get() && (aPartFeature->getKind() == PartSetPlugin_Part::ID()));
830       if (isPart) {
831         DocumentPtr aPartDoc;
832         if (!aPart.get()) {
833           aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aPartFeature->firstResult());
834         }
835         if (aPart.get()) // this may be null is Part feature is disabled
836           aPartDoc = aPart->partDoc();
837         if (aMgr->activeDocument() == aPartDoc)
838           theMenu->addAction(myMenuMgr->action("DEACTIVATE_PART_CMD"));
839         else
840           theMenu->addAction(myMenuMgr->action("ACTIVATE_PART_CMD"));
841       } else if (aObject->document() == aMgr->activeDocument()) {
842         if (hasParameter || hasFeature)
843           theMenu->addAction(myMenuMgr->action("EDIT_CMD"));
844       }
845
846       ResultBodyPtr aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
847       if( aResult.get() )
848       {
849         theMenu->addAction(myMenuMgr->action("SELECT_PARENT_CMD"));
850       }
851     } else {  // If feature is 0 the it means that selected root object (document)
852       if (aMgr->activeDocument() != aMgr->moduleDocument())
853         theMenu->addAction(myMenuMgr->action("ACTIVATE_PARTSET_CMD"));
854     }
855   } else if (aSelected == 0) {
856     // if there is no selection then it means that upper label is selected
857     QModelIndexList aIndexes = myWorkshop->selection()->selectedIndexes();
858     if (aIndexes.size() == 0) // it means that selection happens in top label outside of tree view
859       if (aMgr->activeDocument() != aMgr->moduleDocument())
860         theMenu->addAction(myMenuMgr->action("ACTIVATE_PARTSET_CMD"));
861   }
862   bool aCanDeactivate = (myWorkshop->currentOperation() == 0);
863   myMenuMgr->action("ACTIVATE_PARTSET_CMD")->setEnabled(aCanDeactivate);
864   myMenuMgr->action("DEACTIVATE_PART_CMD")->setEnabled(aCanDeactivate);
865   myMenuMgr->action("ACTIVATE_PART_CMD")->setEnabled(aCanDeactivate);
866 }
867
868 void PartSet_Module::processEvent(const std::shared_ptr<Events_Message>& theMessage)
869 {
870   if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_DOCUMENT_CHANGED)) {
871     // Do not change activation of parts if an operation active
872     static QStringList aAllowActivationList;
873     if (aAllowActivationList.isEmpty())
874       aAllowActivationList << 
875       QString(PartSetPlugin_Part::ID().c_str()) << 
876       QString(PartSetPlugin_Duplicate::ID().c_str()) <<
877       QString(PartSetPlugin_Remove::ID().c_str());
878     if (myWorkshop->currentOperation() && 
879       (!aAllowActivationList.contains(myWorkshop->currentOperation()->id())))
880       return;
881     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myWorkshop);
882     XGUI_Workshop* aWorkshop = aConnector->workshop();
883     XGUI_DataTree* aTreeView = aWorkshop->objectBrowser()->treeView();
884     QLineEdit* aLabel = aWorkshop->objectBrowser()->activeDocLabel();
885     QPalette aPalet = aLabel->palette();
886
887     SessionPtr aMgr = ModelAPI_Session::get();
888     DocumentPtr aActiveDoc = aMgr->activeDocument();
889 #ifdef ModuleDataModel
890     QModelIndex aOldIndex = myDataModel->activePartTree();
891     DocumentPtr aDoc = aMgr->moduleDocument();
892     if (aActiveDoc == aDoc) {
893       if (aOldIndex.isValid())
894         aTreeView->setExpanded(aOldIndex, false);
895       myDataModel->deactivatePart();
896       aPalet.setColor(QPalette::Text, QColor(0, 72, 140));
897     } else {
898       std::string aGrpName = ModelAPI_ResultPart::group();
899       for (int i = 0; i < aDoc->size(aGrpName); i++) {
900         ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aDoc->object(aGrpName, i));
901         if (aPart->partDoc() == aActiveDoc) {
902           QModelIndex aIndex = myDataModel->partIndex(aPart);
903           if (myDataModel->activatePart(aIndex)) {
904             if (aOldIndex.isValid())
905               aTreeView->setExpanded(aOldIndex, false);
906             aTreeView->setExpanded(myDataModel->activePartTree(), true);
907             aPalet.setColor(QPalette::Text, Qt::black);
908           }
909           break;
910         }
911       }
912     }
913 #else
914     // Problem with MPV: At first time on creation it doesn't work because Part feature
915     // creation event will be sent after
916     if (aActivePartIndex.isValid())
917       aTreeView->setExpanded(aActivePartIndex, false);
918     XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
919     aActivePartIndex = aDataModel->documentRootIndex(aActiveDoc);
920     if (aActivePartIndex.isValid())
921       aTreeView->setExpanded(aActivePartIndex, true);
922 #endif
923     aLabel->setPalette(aPalet);
924     aWorkshop->updateCommandStatus();
925
926     // Update displayed objects in order to update active color
927     XGUI_Displayer* aDisplayer = aWorkshop->displayer();
928     QObjectPtrList aObjects = aDisplayer->displayedObjects();
929     foreach(ObjectPtr aObj, aObjects)
930       aDisplayer->redisplay(aObj, false);
931     aDisplayer->updateViewer();
932   }
933 }
934
935 void PartSet_Module::onTreeViewDoubleClick(const QModelIndex& theIndex)
936 {
937   if (myWorkshop->currentOperation()) // Do not change activation of parts if an operation active
938     return;
939   SessionPtr aMgr = ModelAPI_Session::get();
940   if (!theIndex.isValid()) {
941     aMgr->setActiveDocument(aMgr->moduleDocument());
942     return;
943   }
944   if (theIndex.column() != 0) // Use only first column
945     return;
946   ObjectPtr aObj = myDataModel->object(theIndex);
947   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
948   if (!aPart.get()) { // Probably this is Feature
949     FeaturePtr aPartFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
950     if (aPartFeature.get() && (aPartFeature->getKind() == PartSetPlugin_Part::ID())) {
951       aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aPartFeature->firstResult());
952     }
953   }
954   if (aPart.get()) { // if this is a part
955     if (aPart->partDoc() == aMgr->activeDocument()) {
956       aMgr->setActiveDocument(aMgr->moduleDocument());
957     } else {
958       aPart->activate();
959     }
960   }
961 }
962
963
964 void PartSet_Module::onViewCreated(ModuleBase_IViewWindow*)
965 {
966   // z layer is created for all started operations in order to visualize operation AIS presentation
967   // over the object
968   Handle(V3d_Viewer) aViewer = myWorkshop->viewer()->AISContext()->CurrentViewer();
969   if (myVisualLayerId == 0) {
970     if (myVisualLayerId == 0)
971       aViewer->AddZLayer(myVisualLayerId);
972   } else {
973     TColStd_SequenceOfInteger aZList;
974     aViewer->GetAllZLayers(aZList);
975     bool aFound = false;
976     for (int i = 1; i <= aZList.Length(); i++) {
977       if (aZList(i) == myVisualLayerId) {
978         aFound = true;
979         break;
980       }
981     }
982     if (!aFound)
983       aViewer->AddZLayer(myVisualLayerId);
984   }
985 }