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