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