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