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