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