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