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