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