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