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