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