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