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