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