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