]> SALOME platform Git repositories - modules/shaper.git/blob - src/PartSet/PartSet_Module.cpp
Salome HOME
760234e1fd1cb4db515516d168ef4e979c5a8ed4
[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_PreviewPlanes.h"
8 #include "PartSet_WidgetPoint2d.h"
9 #include "PartSet_WidgetPoint2dDistance.h"
10 #include "PartSet_WidgetPoint2DFlyout.h"
11 #include "PartSet_WidgetShapeSelector.h"
12 #include "PartSet_WidgetMultiSelector.h"
13 #include "PartSet_WidgetSubShapeSelector.h"
14 #include "PartSet_WidgetFeaturePointSelector.h"
15 #include "PartSet_WidgetEditor.h"
16 #include "PartSet_WidgetFileSelector.h"
17 #include "PartSet_WidgetSketchCreator.h"
18 #include "PartSet_SketcherMgr.h"
19 #include "PartSet_SketcherReetntrantMgr.h"
20 #include "PartSet_ResultSketchPrs.h"
21 #include "PartSet_MenuMgr.h"
22 #include "PartSet_CustomPrs.h"
23 #include "PartSet_IconFactory.h"
24 #include "PartSet_WidgetChoice.h"
25 #include "PartSet_OverconstraintListener.h"
26
27 #include "PartSet_Filters.h"
28 #include "PartSet_FilterInfinite.h"
29
30 #include <PartSetPlugin_Remove.h>
31 #include <PartSetPlugin_Part.h>
32 #include <PartSetPlugin_Duplicate.h>
33
34 #include <ModuleBase_Operation.h>
35 #include <ModuleBase_OperationAction.h>
36 #include <ModuleBase_IViewer.h>
37 #include <ModuleBase_IViewWindow.h>
38 #include <ModuleBase_IPropertyPanel.h>
39 #include <ModuleBase_WidgetEditor.h>
40 #include <ModuleBase_WidgetValidated.h>
41 #include <ModuleBase_Tools.h>
42 #include <ModuleBase_OperationFeature.h>
43 #include <ModuleBase_WidgetFactory.h>
44 #include <ModuleBase_OperationDescription.h>
45 #include <ModuleBase_ViewerPrs.h>
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_ResultBody.h>
53 #include <ModelAPI_AttributeString.h>
54 #include <ModelAPI_AttributeSelectionList.h>
55 #include <ModelAPI_Tools.h>
56 #include <ModelAPI_ResultConstruction.h>
57
58 #include <GeomDataAPI_Point2D.h>
59 #include <GeomDataAPI_Point.h>
60 #include <GeomDataAPI_Dir.h>
61
62 #include <XGUI_Displayer.h>
63 #include <XGUI_Workshop.h>
64 #include <XGUI_OperationMgr.h>
65 #include <XGUI_PropertyPanel.h>
66 #include <XGUI_ModuleConnector.h>
67 #include <XGUI_ContextMenuMgr.h>
68 #include <XGUI_Tools.h>
69 #include <XGUI_ObjectsBrowser.h>
70 #include <XGUI_SelectionMgr.h>
71 #include <XGUI_DataModel.h>
72 #include <XGUI_ErrorMgr.h>
73 #include <XGUI_CustomPrs.h>
74 #include <XGUI_SelectionMgr.h>
75 #include <XGUI_ActionsMgr.h>
76
77 #include <SketchPlugin_Feature.h>
78 #include <SketchPlugin_Sketch.h>
79 #include <SketchPlugin_ConstraintAngle.h>
80 #include <SketchPlugin_ConstraintLength.h>
81 #include <SketchPlugin_ConstraintDistance.h>
82 #include <SketchPlugin_ConstraintParallel.h>
83 #include <SketchPlugin_ConstraintPerpendicular.h>
84 #include <SketchPlugin_ConstraintRadius.h>
85
86 #include <SketcherPrs_SymbolPrs.h>
87 #include <SketcherPrs_Coincident.h>
88 #include <SketcherPrs_Tools.h>
89
90 #include <Events_Loop.h>
91 #include <Config_PropManager.h>
92 #include <Config_Keywords.h>
93
94 #include <AIS_Dimension.hxx>
95 #include <AIS_InteractiveObject.hxx>
96 #include <StdSelect_TypeOfFace.hxx>
97 #include <TopoDS_Vertex.hxx>
98 #include <TopoDS.hxx>
99 #include <TopoDS_Shape.hxx>
100 #include <BRep_Tool.hxx>
101
102 #include <QObject>
103 #include <QMouseEvent>
104 #include <QString>
105 #include <QTimer>
106 #include <QApplication>
107 #include <QMessageBox>
108 #include <QMainWindow>
109 #include <QLineEdit>
110 #include <QString>
111
112 #include <GeomAlgoAPI_FaceBuilder.h>
113 #include <GeomDataAPI_Dir.h>
114
115 #include <SelectMgr_ListIteratorOfListOfFilter.hxx>
116
117 #ifdef _DEBUG
118 #include <QDebug>
119 #endif
120
121 /*!Create and return new instance of XGUI_Module*/
122 extern "C" PARTSET_EXPORT ModuleBase_IModule* createModule(ModuleBase_IWorkshop* theWshop)
123 {
124   return new PartSet_Module(theWshop);
125 }
126
127 PartSet_Module::PartSet_Module(ModuleBase_IWorkshop* theWshop)
128 : ModuleBase_IModule(theWshop),
129   myVisualLayerId(0),
130   myIsOperationIsLaunched(false)
131 {
132   new PartSet_IconFactory();
133
134   mySketchMgr = new PartSet_SketcherMgr(this);
135   mySketchReentrantMgr = new PartSet_SketcherReetntrantMgr(theWshop);
136
137   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWshop);
138   XGUI_Workshop* aWorkshop = aConnector->workshop();
139
140   ModuleBase_IViewer* aViewer = theWshop->viewer();
141   connect(aViewer, SIGNAL(keyRelease(ModuleBase_IViewWindow*, QKeyEvent*)),
142           this, SLOT(onKeyRelease(ModuleBase_IViewWindow*, QKeyEvent*)));
143   connect(aViewer, SIGNAL(viewTransformed(int)),
144           SLOT(onViewTransformed(int)));
145   connect(aViewer, SIGNAL(viewCreated(ModuleBase_IViewWindow*)),
146           SLOT(onViewCreated(ModuleBase_IViewWindow*)));
147   myMenuMgr = new PartSet_MenuMgr(this);
148   myCustomPrs = new PartSet_CustomPrs(theWshop);
149
150   myOverconstraintListener = new PartSet_OverconstraintListener(theWshop);
151
152   Events_Loop* aLoop = Events_Loop::loop();
153   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_DOCUMENT_CHANGED));
154
155   mySelectionFilters.Append(new PartSet_GlobalFilter(myWorkshop));
156   mySelectionFilters.Append(new PartSet_FilterInfinite(myWorkshop));
157
158   setDefaultConstraintShown();
159
160   Config_PropManager::registerProp("Visualization", "operation_parameter_color",
161                           "Reference shape wireframe color in operation", Config_Prop::Color,
162                           PartSet_CustomPrs::OPERATION_PARAMETER_COLOR());
163   Config_PropManager::registerProp("Visualization", "operation_result_color",
164                           "Result shape wireframe color in operation", Config_Prop::Color,
165                           PartSet_CustomPrs::OPERATION_RESULT_COLOR());
166   Config_PropManager::registerProp("Visualization", "operation_highlight_color",
167                           "Multi selector item color in operation", Config_Prop::Color,
168                           PartSet_CustomPrs::OPERATION_HIGHLIGHT_COLOR());
169   Config_PropManager::registerProp("Visualization", "operation_remove_feature_color",
170                           "Color of removed feature in operation", Config_Prop::Color,
171                           PartSet_CustomPrs::OPERATION_REMOVE_FEATURE_COLOR());
172 }
173
174 PartSet_Module::~PartSet_Module()
175 {
176   SelectMgr_ListIteratorOfListOfFilter aIt(mySelectionFilters);
177   for (; aIt.More(); aIt.Next()) {
178     Handle(SelectMgr_Filter) aFilter = aIt.Value();
179     if (!aFilter.IsNull())
180       aFilter.Nullify();
181   }
182   delete myCustomPrs;
183   delete myOverconstraintListener;
184 }
185
186 void PartSet_Module::activateSelectionFilters()
187 {
188   SelectMgr_ListIteratorOfListOfFilter aIt(mySelectionFilters);
189   for (; aIt.More(); aIt.Next()) {
190     Handle(SelectMgr_Filter) aFilter = aIt.Value();
191     if (!aFilter.IsNull())
192       myWorkshop->viewer()->addSelectionFilter(aFilter);
193   }
194 }
195
196 void PartSet_Module::deactivateSelectionFilters()
197 {
198   SelectMgr_ListIteratorOfListOfFilter aIt(mySelectionFilters);
199   for (; aIt.More(); aIt.Next()) {
200     Handle(SelectMgr_Filter) aFilter = aIt.Value();
201     if (!aFilter.IsNull())
202       myWorkshop->viewer()->removeSelectionFilter(aFilter);
203   }
204 }
205
206 void PartSet_Module::storeSelection()
207 {
208   sketchMgr()->storeSelection();
209 }
210
211 void PartSet_Module::restoreSelection()
212 {
213   sketchMgr()->restoreSelection();
214 }
215
216 void PartSet_Module::registerValidators()
217 {
218   //Registering of validators
219   SessionPtr aMgr = ModelAPI_Session::get();
220   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
221   aFactory->registerValidator("PartSet_DistanceSelection", new PartSet_DistanceSelection);
222   aFactory->registerValidator("PartSet_LengthSelection", new PartSet_LengthSelection);
223   aFactory->registerValidator("PartSet_PerpendicularSelection", new PartSet_PerpendicularSelection);
224   aFactory->registerValidator("PartSet_ParallelSelection", new PartSet_ParallelSelection);
225   aFactory->registerValidator("PartSet_RadiusSelection", new PartSet_RadiusSelection);
226   aFactory->registerValidator("PartSet_RigidSelection", new PartSet_RigidSelection);
227   aFactory->registerValidator("PartSet_CoincidentSelection", new PartSet_CoincidentSelection);
228   aFactory->registerValidator("PartSet_HVDirSelection", new PartSet_HVDirSelection);
229   aFactory->registerValidator("PartSet_TangentSelection", new PartSet_TangentSelection);
230   aFactory->registerValidator("PartSet_FilletSelection", new PartSet_FilletSelection);
231   aFactory->registerValidator("PartSet_AngleSelection", new PartSet_AngleSelection);
232   aFactory->registerValidator("PartSet_EqualSelection", new PartSet_EqualSelection);
233   aFactory->registerValidator("PartSet_CollinearSelection", new PartSet_CollinearSelection);
234   aFactory->registerValidator("PartSet_MiddlePointSelection", new PartSet_MiddlePointSelection);
235   aFactory->registerValidator("PartSet_DifferentObjects", new PartSet_DifferentObjectsValidator);
236   aFactory->registerValidator("PartSet_CoincidentAttr", new PartSet_CoincidentAttr);
237   aFactory->registerValidator("PartSet_MultyTranslationSelection",
238     new PartSet_MultyTranslationSelection);
239   aFactory->registerValidator("PartSet_SplitSelection", new PartSet_SplitSelection);
240   aFactory->registerValidator("PartSet_ProjectionSelection", new PartSet_ProjectionSelection);
241 }
242
243 void PartSet_Module::registerProperties()
244 {
245   Config_PropManager::registerProp(SKETCH_TAB_NAME, "planes_size", "Size", Config_Prop::Double,
246                                    PLANE_SIZE);
247   Config_PropManager::registerProp(SKETCH_TAB_NAME, "planes_thickness", "Thickness",
248                                    Config_Prop::Integer, SKETCH_WIDTH);
249   Config_PropManager::registerProp(SKETCH_TAB_NAME, "rotate_to_plane",
250     "Rotate to plane when selected", Config_Prop::Boolean, "false");
251 }
252
253 void PartSet_Module::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget,
254                                             const bool isToConnect)
255 {
256   mySketchMgr->connectToPropertyPanel(theWidget, isToConnect);
257 }
258
259 void PartSet_Module::operationCommitted(ModuleBase_Operation* theOperation)
260 {
261   if (sketchMgr()->isNestedSketchOperation(theOperation)) {
262     mySketchMgr->commitNestedSketch(theOperation);
263   }
264
265   /// Restart sketcher operations automatically
266   if (!mySketchReentrantMgr->operationCommitted(theOperation)) {
267
268     ModuleBase_OperationFeature* aFOperation =
269       dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
270     if (aFOperation && !aFOperation->isEditOperation()) {
271       // the selection is cleared after commit the create operation
272       // in order to do not use the same selected objects in the restarted operation
273       // for common behaviour, the selection is cleared even if the operation is not restarted
274       getWorkshop()->selector()->clearSelection();
275     }
276   }
277 }
278
279 void PartSet_Module::operationAborted(ModuleBase_Operation* theOperation)
280 {
281   /// Restart sketcher operations automatically
282   mySketchReentrantMgr->operationAborted(theOperation);
283 }
284
285 void PartSet_Module::operationStarted(ModuleBase_Operation* theOperation)
286 {
287   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
288                                                                                 (theOperation);
289   if (aFOperation) {
290     XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(workshop());
291     XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
292
293     ModuleBase_ModelWidget* aFilledWidget = 0;
294     bool aPostonedWidgetActivation = false;
295
296     FeaturePtr aFeature = aFOperation->feature();
297     /// Restart sketcher operations automatically
298     /// it is important to call method of sketch reentrant manager before filling of PP
299     /// because it fills some created feature attributes, these new values should be used
300     /// to fill the property panel
301     mySketchReentrantMgr->operationStarted(theOperation);
302
303     aWorkshop->fillPropertyPanel(aFOperation);
304     // filling the operation values by the current selection
305     // if the operation can be committed after the controls filling, the method perform should
306     // be stopped. Otherwise unnecessary presentations can be shown(e.g. operation prs in sketch)
307     bool isOperationCommitted = false;
308     if (!aFOperation->isEditOperation()) {
309       std::string aGreedAttributeId = ModuleBase_Tools::findGreedAttribute(workshop(), aFeature);
310       // if there is a greed attribute, automatic commit by preselection
311       // for this feature is prohibited
312       aFilledWidget = aFOperation->activateByPreselection(aGreedAttributeId);
313       if (currentOperation() != aFOperation)
314         isOperationCommitted = true;
315       else {
316         if (aGreedAttributeId.empty()) {
317           // a signal should be emitted before the next widget activation
318           // because, the activation of the next widget will give a focus to the widget.
319           // As a result the value of the widget is initialized.
320           // And commit may happens until the value is entered.
321           if (aFilledWidget) {
322             if (mySketchReentrantMgr->canBeCommittedByPreselection())
323               isOperationCommitted = mySketchMgr->operationActivatedByPreselection();
324             // activate the next obligatory widget
325             if (!isOperationCommitted)
326               aPropertyPanel->activateNextWidget(aFilledWidget);
327           }
328         }
329         else { // there is a greed widget
330           const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
331           std::string aFirstAttributeId = aWidgets.front()->attributeID();
332           // activate next widget after greeded if it is the first widget in the panel
333           // else the first panel widget is already activated by operation start
334           if (aFirstAttributeId == aGreedAttributeId)
335             aPostonedWidgetActivation = true;
336         }
337       }
338     } if (!isOperationCommitted) {
339       aWorkshop->connectToPropertyPanel(true);
340       updateSketcherOnStart(aFOperation);
341       updatePresentationsOnStart(aFOperation);
342
343       // the objects of the current operation should be deactivated
344       QObjectPtrList anObjects;
345       anObjects.append(aFeature);
346       std::list<ResultPtr> aResults;
347       ModelAPI_Tools::allResults(aFeature, aResults);
348       std::list<ResultPtr>::const_iterator aIt;
349       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
350         anObjects.append(*aIt);
351       }
352       QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
353       for (; anIt != aLast; anIt++)
354         aWorkshop->deactivateActiveObject(*anIt, false);
355       if (anObjects.size() > 0) {
356         XGUI_Displayer* aDisplayer = aWorkshop->displayer();
357         aDisplayer->updateViewer();
358       }
359       /// state of command actions should be updated after displayed objects modification because
360       /// deactivation(for example) of objects may influence on selection in the viewer
361       /// State of command actions may depend on selection in the viewer(e.g. Sketch)
362       workshop()->updateCommandStatus();
363     }
364     if (aPostonedWidgetActivation) {
365       // if the widget is an empty in the chain of activated widgets, the current operation
366       // is restarted. It should be performed after functionality of the operation starting
367       aPropertyPanel->activateNextWidget(aFilledWidget);
368     }
369   }
370 }
371
372 void PartSet_Module::updateSketcherOnStart(ModuleBase_Operation* theOperation)
373 {
374   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
375     mySketchMgr->startSketch(theOperation);
376   }
377   else if (sketchMgr()->isNestedSketchOperation(theOperation)) {
378     mySketchMgr->startNestedSketch(theOperation);
379   }
380 }
381
382 void PartSet_Module::updatePresentationsOnStart(ModuleBase_Operation* theOperation)
383 {
384   ModuleBase_OperationFeature* aFOperation =
385     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
386   if (aFOperation) {
387     myCustomPrs->activate(aFOperation->feature(), ModuleBase_IModule::CustomizeArguments, true);
388     myCustomPrs->activate(aFOperation->feature(), ModuleBase_IModule::CustomizeResults, true);
389   }
390 }
391
392 void PartSet_Module::operationResumed(ModuleBase_Operation* theOperation)
393 {
394   ModuleBase_IModule::operationResumed(theOperation);
395
396   ModuleBase_OperationFeature* aFOperation =
397     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
398   if (aFOperation) {
399     myCustomPrs->activate(aFOperation->feature(), ModuleBase_IModule::CustomizeArguments, true);
400     myCustomPrs->activate(aFOperation->feature(), ModuleBase_IModule::CustomizeResults, true);
401   }
402 }
403
404 void PartSet_Module::operationStopped(ModuleBase_Operation* theOperation)
405 {
406   bool isModifiedArgs = myCustomPrs->deactivate(ModuleBase_IModule::CustomizeArguments, false);
407   bool isModifiedResults = myCustomPrs->deactivate(ModuleBase_IModule::CustomizeResults, false);
408   bool isModified = isModifiedArgs || isModifiedResults;
409
410   if (sketchMgr()->isNestedSketchOperation(theOperation)) {
411     mySketchMgr->stopNestedSketch(theOperation);
412   }
413   else if (PartSet_SketcherMgr::isSketchOperation(theOperation))
414     setDefaultConstraintShown();
415
416   //VSV: Viewer is updated on feature update and redisplay
417   if (isModified) {
418     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myWorkshop);
419     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
420     aDisplayer->updateViewer();
421   }
422
423   QMap<PartSet_Tools::ConstraintVisibleState, bool>::const_iterator
424     anIt = myHasConstraintShown.begin(), aLast = myHasConstraintShown.end();
425   for (; anIt != aLast; anIt++) {
426     mySketchMgr->updateBySketchParameters(anIt.key(), anIt.value());
427   }
428 }
429
430 ModuleBase_Operation* PartSet_Module::currentOperation() const
431 {
432   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
433   XGUI_OperationMgr* anOpMgr = aConnector->workshop()->operationMgr();
434   return anOpMgr->currentOperation();
435 }
436
437 bool PartSet_Module::canUndo() const
438 {
439   bool aCanUndo = false;
440   SessionPtr aMgr = ModelAPI_Session::get();
441   if (aMgr->hasModuleDocument() && aMgr->canUndo()) {
442     aCanUndo = !aMgr->isOperation();
443     if (!aCanUndo) // check the enable state additionally by sketch manager
444       aCanUndo = aMgr->canUndo();
445   }
446   return aCanUndo;
447 }
448
449 bool PartSet_Module::canRedo() const
450 {
451   bool aCanRedo = false;
452   SessionPtr aMgr = ModelAPI_Session::get();
453   if (aMgr->hasModuleDocument() && aMgr->canRedo()) {
454     aCanRedo = !aMgr->isOperation();
455     if (!aCanRedo) // check the enable state additionally by sketch manager
456       aCanRedo = aMgr->canRedo();
457   }
458   return aCanRedo;
459 }
460
461 bool PartSet_Module::canApplyAction(const ObjectPtr& theObject, const QString& theActionId) const
462 {
463   bool aValid = true;
464   if (theActionId == "MOVE_CMD") {
465     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
466     if (aFeature) {
467       ResultPtr aResult = ModuleBase_Tools::firstResult(aFeature);
468       // part features can not be moved in the history.
469       if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group())
470         aValid = false;
471     }
472   }
473   return aValid;
474 }
475
476 bool PartSet_Module::canEraseObject(const ObjectPtr& theObject) const
477 {
478   // the sketch manager put the restriction to the objects erase
479   return mySketchMgr->canEraseObject(theObject);
480 }
481
482 bool PartSet_Module::canDisplayObject(const ObjectPtr& theObject) const
483 {
484   // the sketch manager put the restriction to the objects display
485   return mySketchMgr->canDisplayObject(theObject);
486 }
487
488 /*void PartSet_Module::processHiddenObject(const std::list<ObjectPtr>& theObjects)
489 {
490   mySketchMgr->processHiddenObject(theObjects);
491 }*/
492
493 bool PartSet_Module::canActivateSelection(const ObjectPtr& theObject) const
494 {
495   bool aCanActivate = ModuleBase_IModule::canActivateSelection(theObject);
496
497   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
498   bool isSketchOp = PartSet_SketcherMgr::isSketchOperation(anOperation),
499        isNestedOp = sketchMgr()->isNestedSketchOperation(anOperation);
500   if (isSketchOp || isNestedOp) {
501     // in active sketch operation it is possible to activate operation object in selection
502     // in the edit operation, e.g. points of the line can be moved when the line is edited
503     ModuleBase_OperationFeature* aFOperation =
504       dynamic_cast<ModuleBase_OperationFeature*>(anOperation);
505     aCanActivate = aCanActivate || (aFOperation && aFOperation->isEditOperation());
506   }
507   return aCanActivate;
508 }
509
510 bool PartSet_Module::addViewerMenu(const QMap<QString, QAction*>& theStdActions,
511                                    QWidget* theParent,
512                                    QMap<int, QAction*>& theMenuActions) const
513 {
514   return myMenuMgr->addViewerMenu(theStdActions, theParent, theMenuActions);
515 }
516
517 void PartSet_Module::updateViewerMenu(const QMap<QString, QAction*>& theStdActions)
518 {
519   myMenuMgr->updateViewerMenu(theStdActions);
520 }
521
522 bool PartSet_Module::isActionEnableStateFixed(const int theActionId) const
523 {
524   bool isEnabledFixed = false;
525   if (theActionId == XGUI_ActionsMgr::AcceptAll &&
526       mySketchReentrantMgr->isInternalEditStarted())
527     isEnabledFixed = true;
528   return isEnabledFixed;
529 }
530
531 QString PartSet_Module::getFeatureError(const FeaturePtr& theFeature)
532 {
533   QString anError = ModuleBase_IModule::getFeatureError(theFeature);
534   if (anError.isEmpty())
535     anError = sketchMgr()->getFeatureError(theFeature);
536
537   return anError;
538 }
539
540 void PartSet_Module::grantedOperationIds(ModuleBase_Operation* theOperation,
541                                          QStringList& theIds) const
542 {
543   myMenuMgr->grantedOperationIds(theOperation, theIds);
544
545   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
546     XGUI_Workshop* aWorkshop = getWorkshop();
547     theIds.append(aWorkshop->contextMenuMgr()->action("DELETE_CMD")->text());
548   }
549 }
550
551 void PartSet_Module::activeSelectionModes(QIntList& theModes)
552 {
553   theModes.clear();
554   if (mySketchMgr->activeSketch().get())
555     PartSet_SketcherMgr::sketchSelectionModes(theModes);
556 }
557
558 void PartSet_Module::customSubShapesSelectionModes(QIntList& theTypes)
559 {
560   if (theTypes.contains(TopAbs_FACE))
561     theTypes.append(SketcherPrs_Tools::Sel_Sketch_Face);
562   if (theTypes.contains(TopAbs_WIRE))
563     theTypes.append(SketcherPrs_Tools::Sel_Sketch_Wire);
564 }
565
566 bool PartSet_Module::isMouseOverWindow()
567 {
568   return mySketchMgr->isMouseOverWindow();
569 }
570
571 bool PartSet_Module::isSketchNeutralPointActivated() const
572 {
573   bool isNeutralPoint = true;
574   if (sketchReentranceMgr()->isInternalEditStarted())
575     isNeutralPoint = false;
576   if (myIsOperationIsLaunched)
577     isNeutralPoint = false;
578
579   return isNeutralPoint;
580 }
581
582 void PartSet_Module::closeDocument()
583 {
584   myActivePartIndex = QModelIndex();
585   clearViewer();
586 }
587
588 void PartSet_Module::clearViewer()
589 {
590   myCustomPrs->clearPrs();
591
592   XGUI_Workshop* aWorkshop = getWorkshop();
593   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
594   aDisplayer->deactivateSelectionFilters();
595 }
596
597 void PartSet_Module::propertyPanelDefined(ModuleBase_Operation* theOperation)
598 {
599   ModuleBase_OperationFeature* aFOperation =
600     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
601   if (!aFOperation)
602     return;
603
604   ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
605   // we have to manually activate the sketch label in edit mode
606   if (PartSet_SketcherMgr::isSketchOperation(aFOperation) &&  (aFOperation->isEditOperation()))
607     aPanel->activateWidget(aPanel->modelWidgets().first());
608 }
609
610 bool PartSet_Module::createWidgets(ModuleBase_Operation* theOperation,
611                                    QList<ModuleBase_ModelWidget*>& theWidgets) const
612 {
613   bool aProcessed = false;
614
615   ModuleBase_OperationFeature* aFOperation =
616     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
617   XGUI_Workshop* aWorkshop = getWorkshop();
618   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
619   if (mySketchMgr->activeSketch().get() && aFOperation && aPropertyPanel) {
620     ModuleBase_ISelection* aSelection = workshop()->selection();
621     // click on a point in sketch leads here with the point is highlighted, not yet selected
622     QList<ModuleBase_ViewerPrsPtr> aPreselection = aSelection->getHighlighted();
623     if (aPreselection.size() == 1) {
624       ModuleBase_ViewerPrsPtr aSelectedPrs = aPreselection[0];
625       ObjectPtr anObject = aSelectedPrs->object();
626
627       FeaturePtr aFeature = ModelAPI_Feature::feature(anObject);
628       FeaturePtr anOpFeature = aFOperation->feature();
629       GeomShapePtr aShape = aSelectedPrs->shape();
630       // click on the digit of dimension constrain comes here
631       // with an empty shape, so we need the check
632       if (aFeature == anOpFeature && aShape.get() && !aShape->isNull()) {
633         // if feature has only one result and shape of result is equal to selected shape
634         // this attribute is not processed. It is a case of Sketch Point.
635         if (aFeature->results().size() == 1) {
636           ResultPtr aResult = aFeature->results().front();
637           if (aResult.get() && aResult->shape()->isEqual(aShape))
638             return aProcessed;
639         }
640         const TopoDS_Shape& aTDShape = aShape->impl<TopoDS_Shape>();
641         AttributePtr anAttribute = PartSet_Tools::findAttributeBy2dPoint(anObject, aTDShape,
642                                                                mySketchMgr->activeSketch());
643         if (anAttribute.get()) {
644           QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
645           ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), workshop());
646
647           const std::string anAttributeId = anAttribute->id();
648           aFactory.createWidget(aPropertyPanel->contentWidget(), anAttributeId);
649
650           theWidgets = aFactory.getModelWidgets();
651           // it is possible that the point does not present in XML definition,
652           // in this case, we assume that it is not processed by this module
653           // e.g. "Intersection point" feature
654           aProcessed = !theWidgets.isEmpty();
655         }
656       }
657     }
658   }
659   return aProcessed;
660 }
661
662 void PartSet_Module::onSelectionChanged()
663 {
664   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
665   if (!aOperation)
666     return;
667
668   bool isSketcherOp = false;
669   // An edit operation is enable only if the current opeation is the sketch operation
670   if (mySketchMgr->activeSketch()) {
671     if (PartSet_Tools::sketchPlane(mySketchMgr->activeSketch()))
672       isSketcherOp = PartSet_SketcherMgr::isSketchOperation(aOperation);
673   }
674   if (isSketcherOp) {
675     // Editing of constraints can be done on selection
676     ModuleBase_ISelection* aSelect = myWorkshop->selection();
677     QList<ModuleBase_ViewerPrsPtr> aSelected = aSelect->getSelected();
678     if (aSelected.size() == 1) {
679       ModuleBase_ViewerPrsPtr aPrs = aSelected.first();
680       ObjectPtr aObject = aPrs->object();
681       FeaturePtr aFeature = ModelAPI_Feature::feature(aObject);
682       if (aFeature) {
683         std::string aId = aFeature->getKind();
684         if ((aId == SketchPlugin_ConstraintRadius::ID()) ||
685             (aId == SketchPlugin_ConstraintLength::ID()) ||
686             (aId == SketchPlugin_ConstraintDistance::ID()) ||
687             (aId == SketchPlugin_ConstraintAngle::ID())) {
688           editFeature(aFeature);
689         }
690       }
691     }
692   }
693 }
694
695 void PartSet_Module::onKeyRelease(ModuleBase_IViewWindow* theWnd, QKeyEvent* theEvent)
696 {
697   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
698   XGUI_OperationMgr* anOpMgr = aConnector->workshop()->operationMgr();
699   anOpMgr->onKeyReleased(theWnd->viewPort(), theEvent);
700 }
701
702 ModuleBase_ModelWidget* PartSet_Module::createWidgetByType(const std::string& theType,
703                                                            QWidget* theParent,
704                                                            Config_WidgetAPI* theWidgetApi)
705 {
706   ModuleBase_IWorkshop* aWorkshop = workshop();
707   XGUI_Workshop* aXUIWorkshop = getWorkshop();
708   ModuleBase_ModelWidget* aWgt = NULL;
709   if (theType == "sketch-start-label") {
710     PartSet_WidgetSketchLabel* aLabelWgt = new PartSet_WidgetSketchLabel(theParent, aWorkshop,
711                                                                theWidgetApi, myHasConstraintShown);
712     connect(aLabelWgt, SIGNAL(planeSelected(const std::shared_ptr<GeomAPI_Pln>&)),
713       mySketchMgr, SLOT(onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>&)));
714     connect(aLabelWgt, SIGNAL(showConstraintToggled(int, bool)),
715       mySketchMgr, SLOT(onShowConstraintsToggle(int, bool)));
716     aWgt = aLabelWgt;
717   } else if (theType == "sketch-2dpoint_selector") {
718     PartSet_WidgetPoint2D* aPointWgt = new PartSet_WidgetPoint2D(theParent, aWorkshop,
719                                                                  theWidgetApi);
720     aPointWgt->setSketch(mySketchMgr->activeSketch());
721     connect(aPointWgt, SIGNAL(vertexSelected()), sketchReentranceMgr(), SLOT(onVertexSelected()));
722     aWgt = aPointWgt;
723   }else if (theType == "sketch-2dpoint_flyout_selector") {
724     PartSet_WidgetPoint2DFlyout* aPointWgt = new PartSet_WidgetPoint2DFlyout(theParent, aWorkshop,
725                                                                              theWidgetApi);
726     aPointWgt->setSketch(mySketchMgr->activeSketch());
727     connect(aPointWgt, SIGNAL(vertexSelected()), sketchReentranceMgr(), SLOT(onVertexSelected()));
728     aWgt = aPointWgt;
729   } else if (theType == "point2ddistance") {
730     PartSet_WidgetPoint2dDistance* aDistanceWgt = new PartSet_WidgetPoint2dDistance(theParent,
731                                                                      aWorkshop, theWidgetApi);
732     aDistanceWgt->setSketch(mySketchMgr->activeSketch());
733     aWgt = aDistanceWgt;
734   } else if (theType == "sketch_shape_selector") {
735     PartSet_WidgetShapeSelector* aShapeSelectorWgt =
736                           new PartSet_WidgetShapeSelector(theParent, aWorkshop, theWidgetApi);
737     aShapeSelectorWgt->setSketcher(mySketchMgr->activeSketch());
738     aWgt = aShapeSelectorWgt;
739   } else if (theType == "sketch_multi_selector") {
740     PartSet_WidgetMultiSelector* aShapeSelectorWgt =
741                           new PartSet_WidgetMultiSelector(theParent, aWorkshop, theWidgetApi);
742     aShapeSelectorWgt->setSketcher(mySketchMgr->activeSketch());
743     aWgt = aShapeSelectorWgt;
744   }
745   else if (theType == "sketch_sub_shape_selector") {
746     PartSet_WidgetSubShapeSelector* aSubShapeSelectorWgt =
747                           new PartSet_WidgetSubShapeSelector(theParent, aWorkshop, theWidgetApi);
748     aSubShapeSelectorWgt->setSketcher(mySketchMgr->activeSketch());
749     aWgt = aSubShapeSelectorWgt;
750   }
751   else if (theType == "sketch_feature_point_selector") {
752     PartSet_WidgetFeaturePointSelector* aPointSelectorWgt =
753             new PartSet_WidgetFeaturePointSelector(theParent, aWorkshop, theWidgetApi);
754     aPointSelectorWgt->setSketcher(mySketchMgr->activeSketch());
755     aWgt = aPointSelectorWgt;
756   }
757   else if (theType == WDG_DOUBLEVALUE_EDITOR) {
758     aWgt = new PartSet_WidgetEditor(theParent, aWorkshop, theWidgetApi);
759   } else if (theType == "export_file_selector") {
760     aWgt = new PartSet_WidgetFileSelector(theParent, aWorkshop, theWidgetApi);
761   } else if (theType == "sketch_launcher") {
762     aWgt = new PartSet_WidgetSketchCreator(theParent, this, theWidgetApi);
763   } else if (theType == "module_choice") {
764     aWgt = new PartSet_WidgetChoice(theParent, theWidgetApi);
765     connect(aWgt, SIGNAL(itemSelected(ModuleBase_ModelWidget*, int)),
766             this, SLOT(onChoiceChanged(ModuleBase_ModelWidget*, int)));
767   }
768   return aWgt;
769 }
770
771 ModuleBase_ModelWidget* PartSet_Module::activeWidget() const
772 {
773   ModuleBase_ModelWidget* anActiveWidget = 0;
774
775   anActiveWidget = mySketchReentrantMgr->internalActiveWidget();
776   if (!anActiveWidget) {
777     ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
778     if (aOperation) {
779       ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
780       anActiveWidget = aPanel ? aPanel->activeWidget() : 0;
781     }
782   }
783   return anActiveWidget;
784 }
785
786 bool PartSet_Module::deleteObjects()
787 {
788   bool isProcessed = false;
789
790   XGUI_Workshop* aWorkshop = getWorkshop();
791   XGUI_OperationMgr* anOpMgr = aWorkshop->operationMgr();
792
793   //SessionPtr aMgr = ModelAPI_Session::get();
794   // 1. check whether the delete should be processed in the module
795   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
796   bool isSketchOp = PartSet_SketcherMgr::isSketchOperation(anOperation),
797        isNestedOp = sketchMgr()->isNestedSketchOperation(anOperation);
798   if (isSketchOp || isNestedOp) {
799     isProcessed = true;
800     // 2. find selected presentations
801     // selected objects should be collected before the current operation abort because
802     // the abort leads to selection lost on constraint objects. It can be corrected after #386 issue
803     ModuleBase_ISelection* aSel = workshop()->selection();
804     QObjectPtrList aSelectedObj = aSel->selectedPresentations();
805     // if there are no selected objects in the viewer, that means that the selection in another
806     // place cased this method. It is necessary to return the false value to understande in above
807     // method that delete is not processed
808     if (aSelectedObj.count() == 0)
809       return false;
810
811     // avoid delete of the objects, which are not belong to the current sketch
812     // in order to do not delete results of other sketches
813     QObjectPtrList aSketchObjects;
814     QObjectPtrList::const_iterator anIt = aSelectedObj.begin(), aLast = aSelectedObj.end();
815     for ( ; anIt != aLast; anIt++) {
816       ObjectPtr anObject = *anIt;
817       if (mySketchMgr->isObjectOfSketch(anObject)) {
818         // sketch feature should be used in this list because workshop deletes features only
819         // results are skipped
820         FeaturePtr aSketchFeature = ModelAPI_Feature::feature(anObject);
821         aSketchObjects.append(aSketchFeature);
822       }
823     }
824     // if the selection contains only local selected presentations from other sketches,
825     // the Delete operation should not be done at all
826     if (aSketchObjects.size() == 0)
827       return true;
828
829     // 3. start operation
830     QString aDescription = aWorkshop->contextMenuMgr()->action("DELETE_CMD")->text();
831     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, this);
832
833     // the active nested sketch operation should be aborted unconditionally
834     // the Delete action should be additionally granted for the Sketch operation
835     // in order to do not abort/commit it
836     if (!anOpMgr->canStartOperation(anOpAction->id()))
837       return true; // the objects are processed but can not be deleted
838
839     anOpMgr->startOperation(anOpAction);
840
841     // WORKAROUND, should be done to avoid viewer highlight update after deletetion of objects
842     // the problem is in AIS Dimensions recompute
843     // if a line and the dim are removed, line is the first
844     // it causes the AIS recompute, where the base line is null,
845     // the result is empty AIS in the viewer
846     XGUI_Tools::workshop(myWorkshop)->selector()->clearSelection();
847
848     // 4. delete features
849     // sketch feature should be skipped, only sub-features can be removed
850     // when sketch operation is active
851     aWorkshop->deleteFeatures(aSketchObjects);
852     // 5. stop operation
853     anOpMgr->commitOperation();
854   }
855   return isProcessed;
856 }
857
858 void PartSet_Module::onFeatureTriggered()
859 {
860   // is commented for imp: Unpressing the button of the current action must behave like
861   // a validation if the entity can be created (instead of Cancel, as currently)
862   /*QAction* aCmd = dynamic_cast<QAction*>(sender());
863   if (aCmd->isCheckable() && aCmd->isChecked()) {
864     // 1. check whether the delete should be processed in the module
865     ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
866     bool isNestedOp = myModule->sketchMgr()->isNestedCreateOperation(anOperation);
867     if (isNestedOp) {
868       // in case if in the viewer nothing is displayed, the create operation should not be
869       // comitted even if all values of the feature are initialized
870       if (!mySketchMgr->canDisplayCurrentCreatedFeature()) {
871         // the action information should be saved before the operation is aborted
872         // because this abort leads to update command status, which unchecks this action
873         anOperation->abort();
874         launchOperation(aCmd->data().toString());
875       }
876     }
877   }*/
878   ModuleBase_IModule::onFeatureTriggered();
879 }
880
881 void PartSet_Module::editFeature(FeaturePtr theFeature)
882 {
883   storeConstraintsState(theFeature->getKind());
884   ModuleBase_IModule::editFeature(theFeature);
885 }
886
887 bool PartSet_Module::canCommitOperation() const
888 {
889   return true;
890 }
891
892 void PartSet_Module::launchOperation(const QString& theCmdId)
893 {
894   myIsOperationIsLaunched = true;
895   storeConstraintsState(theCmdId.toStdString());
896   updateConstraintsState(theCmdId.toStdString());
897
898   ModuleBase_IModule::launchOperation(theCmdId);
899
900   myIsOperationIsLaunched = false;
901 }
902
903 void PartSet_Module::storeConstraintsState(const std::string& theFeatureKind)
904 {
905   if (myWorkshop->currentOperation() &&
906       myWorkshop->currentOperation()->id().toStdString() == SketchPlugin_Sketch::ID()) {
907     const QMap<PartSet_Tools::ConstraintVisibleState, bool>& aShownStates =
908                                                   mySketchMgr->showConstraintStates();
909     myHasConstraintShown = aShownStates;
910   }
911 }
912
913 void PartSet_Module::updateConstraintsState(const std::string& theFeatureKind)
914 {
915   if (PartSet_SketcherMgr::constraintsIdList().contains(theFeatureKind.c_str()) ||
916       PartSet_SketcherMgr::replicationsIdList().contains(theFeatureKind.c_str())) {
917     // Show constraints if a constraint was anOperation
918     mySketchMgr->updateBySketchParameters(PartSet_Tools::Geometrical, true);
919     mySketchMgr->updateBySketchParameters(PartSet_Tools::Dimensional, true);
920     mySketchMgr->updateBySketchParameters(PartSet_Tools::Expressions,
921                                           myHasConstraintShown[PartSet_Tools::Expressions]);
922   }
923 }
924
925 void PartSet_Module::onObjectDisplayed(ObjectPtr theObject, AISObjectPtr theAIS)
926 {
927   Handle(AIS_InteractiveObject) anAIS = theAIS->impl<Handle(AIS_InteractiveObject)>();
928   if (!anAIS.IsNull()) {
929     Handle(AIS_InteractiveContext) aCtx = anAIS->GetContext();
930     Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(anAIS);
931     if (!aDim.IsNull()) {
932       aCtx->SetZLayer(aDim, myVisualLayerId);
933     } else {
934       Handle(SketcherPrs_SymbolPrs) aCons = Handle(SketcherPrs_SymbolPrs)::DownCast(anAIS);
935       if (!aCons.IsNull())
936         aCtx->SetZLayer(aCons, myVisualLayerId);
937     }
938   }
939 }
940
941 void PartSet_Module::onBeforeObjectErase(ObjectPtr theObject, AISObjectPtr theAIS)
942 {
943   // this is obsolete
944   // it should be recomputed in order to disappear in the viewer if the corresponded object
945   // is erased
946   //if (myCustomPrs->isActive())
947   //  myCustomPrs->redisplay(theObject, false);
948 }
949
950 void PartSet_Module::onViewTransformed(int theTrsfType)
951 {
952   // Set length of arrows constant in pixel size
953   // if the operation is panning or rotate or panglobal then do nothing
954   if ((theTrsfType == 1) || (theTrsfType == 3) || (theTrsfType == 4))
955     return;
956   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
957   Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
958   if (aContext.IsNull())
959     return;
960
961   //Handle(V3d_View) aView = aViewer->activeView();
962
963   XGUI_Workshop* aWorkshop = getWorkshop();
964   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
965   Handle(V3d_Viewer) aV3dViewer = aContext->CurrentViewer();
966   Handle(V3d_View) aView;
967   double aScale = 0;
968   for (aV3dViewer->InitDefinedViews();
969        aV3dViewer->MoreDefinedViews();
970        aV3dViewer->NextDefinedViews()) {
971     Handle(V3d_View) aV = aV3dViewer->DefinedView();
972     double aS = aV->Scale();
973     if (aS > aScale) {
974       aScale = aS;
975       aView = aV;
976     }
977   }
978   if (aView.IsNull())
979     return;
980   double aLen = aView->Convert(SketcherPrs_Tools::getDefaultArrowSize());
981
982   double aPrevLen = SketcherPrs_Tools::getArrowSize();
983   SketcherPrs_Tools::setArrowSize(aLen);
984   const double aPrevScale = aViewer->Scale(aViewer->activeView());
985   const double aCurScale = aViewer->activeView()->Camera()->Scale();
986   aViewer->SetScale(aViewer->activeView(), aCurScale);
987   SketcherPrs_Tools::setTextHeight (aCurScale / aPrevScale * SketcherPrs_Tools::getTextHeight());
988   bool isModified = false;
989   QList<AISObjectPtr> aPrsList = aDisplayer->displayedPresentations();
990   foreach (AISObjectPtr aAIS, aPrsList) {
991     Handle(AIS_InteractiveObject) aAisObj = aAIS->impl<Handle(AIS_InteractiveObject)>();
992
993     Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(aAisObj);
994     if (!aDim.IsNull()) {
995       aDim->DimensionAspect()->ArrowAspect()->SetLength(aLen);
996       aContext->Redisplay(aDim, false);
997       isModified = true;
998     }
999   }
1000   if (isModified)
1001     aDisplayer->updateViewer();
1002 }
1003
1004 bool PartSet_Module::isCustomPrsActivated(const ModuleBase_CustomizeFlag& theFlag) const
1005 {
1006   return myCustomPrs->isActive(theFlag);
1007 }
1008
1009 void PartSet_Module::activateCustomPrs(const FeaturePtr& theFeature,
1010                                        const ModuleBase_CustomizeFlag& theFlag,
1011                                        const bool theUpdateViewer)
1012 {
1013   myCustomPrs->activate(theFeature, theFlag, theUpdateViewer);
1014 }
1015
1016 void PartSet_Module::deactivateCustomPrs(const ModuleBase_CustomizeFlag& theFlag,
1017                                          const bool theUpdateViewer)
1018 {
1019   myCustomPrs->deactivate(theFlag, theUpdateViewer);
1020 }
1021
1022 bool PartSet_Module::customisePresentation(ResultPtr theResult, AISObjectPtr thePrs,
1023                                            std::shared_ptr<GeomAPI_ICustomPrs> theCustomPrs)
1024 {
1025   bool aCustomized = false;
1026
1027   XGUI_Workshop* aWorkshop = getWorkshop();
1028   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1029   ObjectPtr anObject = aDisplayer->getObject(thePrs);
1030   if (!anObject)
1031     return aCustomized;
1032
1033   if (!theResult.get()) {
1034     bool isConflicting = myOverconstraintListener->isConflictingObject(anObject);
1035     // customize sketch symbol presentation
1036     if (thePrs.get()) {
1037       Handle(AIS_InteractiveObject) anAISIO = thePrs->impl<Handle(AIS_InteractiveObject)>();
1038       if (!anAISIO.IsNull()) {
1039         if (!Handle(SketcherPrs_SymbolPrs)::DownCast(anAISIO).IsNull()) {
1040           Handle(SketcherPrs_SymbolPrs) aPrs = Handle(SketcherPrs_SymbolPrs)::DownCast(anAISIO);
1041           if (!aPrs.IsNull()) {
1042             std::vector<int> aColor;
1043             myOverconstraintListener->getConflictingColor(aColor);
1044             aPrs->SetConflictingConstraint(isConflicting, aColor);
1045             aCustomized = true;
1046           }
1047         } else if (!Handle(SketcherPrs_Coincident)::DownCast(anAISIO).IsNull()) {
1048           Handle(SketcherPrs_Coincident) aPrs = Handle(SketcherPrs_Coincident)::DownCast(anAISIO);
1049           if (!aPrs.IsNull()) {
1050             std::vector<int> aColor;
1051             myOverconstraintListener->getConflictingColor(aColor);
1052             aPrs->SetConflictingConstraint(isConflicting, aColor);
1053             aCustomized = true;
1054           }
1055         }
1056       }
1057     }
1058     // customize sketch dimension constraint presentation
1059     if (!aCustomized) {
1060       std::vector<int> aColor;
1061       if (isConflicting) {
1062         myOverconstraintListener->getConflictingColor(aColor);
1063       }
1064       if (aColor.empty())
1065         XGUI_CustomPrs::getDefaultColor(anObject, true, aColor);
1066       if (!aColor.empty()) {
1067         aCustomized = thePrs->setColor(aColor[0], aColor[1], aColor[2]);
1068       }
1069     }
1070   }
1071   // customize dimentional constrains
1072   sketchMgr()->customizePresentation(anObject);
1073
1074   return aCustomized;
1075 }
1076
1077 bool PartSet_Module::customizeObject(ObjectPtr theObject, const ModuleBase_CustomizeFlag& theFlag,
1078                                      const bool theUpdateViewer)
1079 {
1080   bool isRedisplayed = false;
1081   if (myCustomPrs->isActive(theFlag))
1082     isRedisplayed = myCustomPrs->redisplay(theObject, theFlag, theUpdateViewer);
1083
1084   return isRedisplayed;
1085 }
1086
1087 void PartSet_Module::customizeObjectBrowser(QWidget* theObjectBrowser)
1088 {
1089   XGUI_ObjectsBrowser* aOB = dynamic_cast<XGUI_ObjectsBrowser*>(theObjectBrowser);
1090   if (aOB) {
1091     QLabel* aLabel = aOB->activeDocLabel();
1092     aLabel->installEventFilter(myMenuMgr);
1093     connect(aLabel, SIGNAL(customContextMenuRequested(const QPoint&)),
1094           SLOT(onActiveDocPopup(const QPoint&)));
1095     aOB->treeView()->setExpandsOnDoubleClick(false);
1096     connect(aOB->treeView(), SIGNAL(doubleClicked(const QModelIndex&)),
1097       SLOT(onTreeViewDoubleClick(const QModelIndex&)));
1098
1099     Events_Loop* aLoop = Events_Loop::loop();
1100     aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1101   }
1102 }
1103
1104 void PartSet_Module::onActiveDocPopup(const QPoint& thePnt)
1105 {
1106   SessionPtr aMgr = ModelAPI_Session::get();
1107   QAction* aActivatePartAction = myMenuMgr->action("ACTIVATE_PARTSET_CMD");
1108
1109   XGUI_Workshop* aWorkshop = getWorkshop();
1110   QLabel* aHeader = aWorkshop->objectBrowser()->activeDocLabel();
1111
1112   aActivatePartAction->setEnabled((aMgr->activeDocument() != aMgr->moduleDocument()));
1113
1114   QMenu aMenu;
1115   aMenu.addAction(aActivatePartAction);
1116   aMenu.exec(aHeader->mapToGlobal(thePnt));
1117 }
1118
1119 Handle(AIS_InteractiveObject) PartSet_Module::createPresentation(const ResultPtr& theResult)
1120 {
1121   return mySketchMgr->createPresentation(theResult);
1122 }
1123
1124
1125 ObjectPtr PartSet_Module::findPresentedObject(const AISObjectPtr& theAIS) const
1126 {
1127   ObjectPtr anObject;
1128   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1129   if (aOperation) {
1130     /// If last line finished on vertex the lines creation sequence has to be break
1131     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
1132     if (aPanel) {
1133       ModuleBase_ModelWidget* anActiveWidget = aPanel->activeWidget();
1134       // if there is an active widget, find the presented object in it
1135       if (!anActiveWidget)
1136         anActiveWidget = aPanel->preselectionWidget();
1137
1138       ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
1139                                                                              (anActiveWidget);
1140       if (aWidgetValidated)
1141         anObject = aWidgetValidated->findPresentedObject(theAIS);
1142     }
1143   }
1144   return anObject;
1145 }
1146
1147 bool PartSet_Module::canBeShaded(Handle(AIS_InteractiveObject) theAIS) const
1148 {
1149   bool aCanBeShaged = true;
1150
1151   Handle(PartSet_ResultSketchPrs) aPrs = Handle(PartSet_ResultSketchPrs)::DownCast(theAIS);
1152   if (!aPrs.IsNull())
1153     aCanBeShaged = false;
1154
1155   return aCanBeShaged;
1156 }
1157
1158 void PartSet_Module::addObjectBrowserMenu(QMenu* theMenu) const
1159 {
1160   QObjectPtrList aObjects = myWorkshop->selection()->selectedObjects();
1161   int aSelected = aObjects.size();
1162   SessionPtr aMgr = ModelAPI_Session::get();
1163   QAction* aActivatePartAction = myMenuMgr->action("ACTIVATE_PART_CMD");
1164
1165   bool hasResult = false;
1166   bool hasFeature = false;
1167   bool hasParameter = false;
1168   bool hasCompositeOwner = false;
1169   ModuleBase_Tools::checkObjects(aObjects, hasResult, hasFeature, hasParameter,
1170                                   hasCompositeOwner);
1171
1172   ModuleBase_Operation* aCurrentOp = myWorkshop->currentOperation();
1173   if (aSelected == 1) {
1174     ObjectPtr aObject = aObjects.first();
1175     if (aObject) {
1176       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1177       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1178       bool isPart = aPart.get() ||
1179         (aFeature.get() && (aFeature->getKind() == PartSetPlugin_Part::ID()));
1180       if (isPart) {
1181         DocumentPtr aPartDoc;
1182         if (!aPart.get()) {
1183           aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFeature->firstResult());
1184         }
1185         if (aPart.get()) // this may be null is Part feature is disabled
1186           aPartDoc = aPart->partDoc();
1187
1188         theMenu->addAction(aActivatePartAction);
1189         aActivatePartAction->setEnabled((aMgr->activeDocument() != aPartDoc));
1190
1191       } else if (aObject->document() == aMgr->activeDocument()) {
1192         if (hasParameter || hasFeature) {
1193           myMenuMgr->action("EDIT_CMD")->setEnabled(true);
1194           theMenu->addAction(myMenuMgr->action("EDIT_CMD"));
1195           if (aCurrentOp && aFeature.get()) {
1196             if (aCurrentOp->id().toStdString() == aFeature->getKind())
1197               myMenuMgr->action("EDIT_CMD")->setEnabled(false);
1198           }
1199         }
1200       }
1201     }
1202   } else {
1203     if (hasFeature) {
1204       myMenuMgr->action("EDIT_CMD")->setEnabled(aCurrentOp == 0);
1205       theMenu->addAction(myMenuMgr->action("EDIT_CMD"));
1206       theMenu->addSeparator();
1207     }
1208   }
1209   bool aNotDeactivate = (aCurrentOp == 0);
1210   if (!aNotDeactivate) {
1211     aActivatePartAction->setEnabled(false);
1212   }
1213 }
1214
1215 #define EXPAND_PARENT(OBJ) \
1216 QModelIndex aObjIndex = aDataModel->objectIndex(OBJ); \
1217 if (aObjIndex.isValid()) { \
1218   QModelIndex aParent = aObjIndex.parent(); \
1219   int aCount = aDataModel->rowCount(aParent); \
1220   if (aCount == 1) \
1221     aTreeView->setExpanded(aParent, true); \
1222 }
1223
1224
1225 void PartSet_Module::processEvent(const std::shared_ptr<Events_Message>& theMessage)
1226 {
1227   if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_DOCUMENT_CHANGED)) {
1228     // Do not change activation of parts if an operation active
1229     static QStringList aAllowActivationList;
1230     if (aAllowActivationList.isEmpty())
1231       aAllowActivationList <<
1232       QString(PartSetPlugin_Part::ID().c_str()) <<
1233       QString(PartSetPlugin_Duplicate::ID().c_str()) <<
1234       QString(PartSetPlugin_Remove::ID().c_str());
1235     if (myWorkshop->currentOperation() &&
1236       (!aAllowActivationList.contains(myWorkshop->currentOperation()->id())))
1237       return;
1238     XGUI_Workshop* aWorkshop = getWorkshop();
1239     XGUI_DataTree* aTreeView = aWorkshop->objectBrowser()->treeView();
1240     QLabel* aLabel = aWorkshop->objectBrowser()->activeDocLabel();
1241     QPalette aPalet = aLabel->palette();
1242
1243     SessionPtr aMgr = ModelAPI_Session::get();
1244     DocumentPtr aActiveDoc = aMgr->activeDocument();
1245     if (myActivePartIndex.isValid())
1246       aTreeView->setExpanded(myActivePartIndex, false);
1247     XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1248     myActivePartIndex = aDataModel->documentRootIndex(aActiveDoc);
1249     if (myActivePartIndex.isValid())
1250       aTreeView->setExpanded(myActivePartIndex, true);
1251
1252     aLabel->setPalette(aPalet);
1253     aWorkshop->updateCommandStatus();
1254
1255     // Update displayed objects in order to update active color
1256     XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1257     QObjectPtrList aObjects = aDisplayer->displayedObjects();
1258     bool aHidden;
1259     foreach(ObjectPtr aObj, aObjects) {
1260       aHidden = !aObj->data() || !aObj->data()->isValid() ||
1261         aObj->isDisabled() || (!aObj->isDisplayed());
1262       if (!aHidden)
1263         aDisplayer->redisplay(aObj, false);
1264     }
1265     aDisplayer->updateViewer();
1266   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
1267     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
1268         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
1269     std::set<ObjectPtr> aObjects = aUpdMsg->objects();
1270
1271     ObjectPtr aConstrObj;
1272     ObjectPtr aResultObj;
1273     std::set<ObjectPtr>::const_iterator aIt;
1274     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
1275     for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
1276       ObjectPtr aObject = (*aIt);
1277       if ((!aResultObj.get()) && (aObject->groupName() == ModelAPI_ResultBody::group())
1278           && (aObject->document() != aRootDoc))
1279         aResultObj = aObject;
1280       if ((!aConstrObj.get()) && (aObject->groupName() == ModelAPI_ResultConstruction::group())
1281           && (aObject->document() != aRootDoc))
1282         aConstrObj = aObject;
1283       if (aResultObj.get() && aConstrObj.get())
1284         break;
1285     }
1286
1287     if (aResultObj.get() || aConstrObj.get()) {
1288       XGUI_Workshop* aWorkshop = getWorkshop();
1289       XGUI_DataTree* aTreeView = aWorkshop->objectBrowser()->treeView();
1290       XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1291
1292       if (aResultObj.get()) {
1293         EXPAND_PARENT(aResultObj)
1294       }
1295       if (aConstrObj.get()) {
1296         EXPAND_PARENT(aConstrObj)
1297       }
1298     }
1299   }
1300 }
1301
1302 void PartSet_Module::onTreeViewDoubleClick(const QModelIndex& theIndex)
1303 {
1304   if (myWorkshop->currentOperation()) // Do not change activation of parts if an operation active
1305     return;
1306   SessionPtr aMgr = ModelAPI_Session::get();
1307   if (!theIndex.isValid()) {
1308     // It seems that this code is obsolete
1309     //aMgr->setActiveDocument(aMgr->moduleDocument());
1310     return;
1311   }
1312   if (theIndex.column() != 0) // Use only first column
1313     return;
1314
1315   XGUI_Workshop* aWorkshop = getWorkshop();
1316   XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1317   // De not use non editable Indexes
1318   if ((aDataModel->flags(theIndex) & Qt::ItemIsSelectable) == 0)
1319     return;
1320   ObjectPtr aObj = aDataModel->object(theIndex);
1321
1322   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1323   if (!aPart.get()) { // Probably this is Feature
1324     FeaturePtr aPartFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
1325     if (aPartFeature.get() && (aPartFeature->getKind() == PartSetPlugin_Part::ID())) {
1326       aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aPartFeature->firstResult());
1327     }
1328   }
1329   if (aPart.get()) { // if this is a part
1330     if (aPart->partDoc() == aMgr->activeDocument()) {
1331       myMenuMgr->activatePartSet();
1332     } else {
1333       myMenuMgr->activatePart(aPart);
1334     }
1335   }
1336 }
1337
1338
1339 void PartSet_Module::onViewCreated(ModuleBase_IViewWindow*)
1340 {
1341   // z layer is created for all started operations in order to visualize operation AIS presentation
1342   // over the object
1343   Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
1344   if (aContext.IsNull())
1345     return;
1346
1347   Handle(V3d_Viewer) aViewer = aContext->CurrentViewer();
1348   if (myVisualLayerId == 0) {
1349     if (myVisualLayerId == 0)
1350       aViewer->AddZLayer(myVisualLayerId);
1351   } else {
1352     TColStd_SequenceOfInteger aZList;
1353     aViewer->GetAllZLayers(aZList);
1354     bool aFound = false;
1355     for (int i = 1; i <= aZList.Length(); i++) {
1356       if (aZList(i) == myVisualLayerId) {
1357         aFound = true;
1358         break;
1359       }
1360     }
1361     if (!aFound)
1362       aViewer->AddZLayer(myVisualLayerId);
1363   }
1364   // if there is an active operation with validated widget,
1365   // the filters of this widget should be activated in the created view
1366   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1367   if (aOperation) {
1368     ModuleBase_ModelWidget* anActiveWidget = activeWidget();
1369     if (anActiveWidget) {
1370       ModuleBase_WidgetSelector* aWSelector =
1371         dynamic_cast<ModuleBase_WidgetSelector*>(anActiveWidget);
1372       if (aWSelector)
1373         aWSelector->activateSelectionAndFilters(true);
1374     }
1375   }
1376 }
1377
1378 //******************************************************
1379 void PartSet_Module::widgetStateChanged(int thePreviousState)
1380 {
1381   mySketchMgr->widgetStateChanged(thePreviousState);
1382 }
1383
1384 bool PartSet_Module::processEnter(const std::string& thePreviousAttributeID)
1385 {
1386   return mySketchReentrantMgr->processEnter(thePreviousAttributeID);
1387 }
1388
1389 //******************************************************
1390 void PartSet_Module::beforeOperationStopped(ModuleBase_Operation* theOperation)
1391 {
1392   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
1393     mySketchMgr->stopSketch(theOperation);
1394   }
1395 }
1396
1397 //******************************************************
1398 GeomShapePtr PartSet_Module::findShape(const AttributePtr& theAttribute)
1399 {
1400   GeomShapePtr aGeomShape;
1401
1402   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
1403   if (anOperation && sketchMgr()->isNestedSketchOperation(anOperation)) {
1404     aGeomShape = PartSet_Tools::findShapeBy2DPoint(theAttribute, myWorkshop);
1405   }
1406   return aGeomShape;
1407 }
1408
1409 //******************************************************
1410 AttributePtr PartSet_Module::findAttribute(const ObjectPtr& theObject,
1411                                            const GeomShapePtr& theGeomShape)
1412 {
1413   AttributePtr anAttribute;
1414   GeomShapePtr aGeomShape = theGeomShape;
1415   if (!aGeomShape.get()) {
1416     // processing shape of result, e.g. sketch circle center is selected, this is a result
1417     // the geom shape is empty, the shape of result should be used
1418     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1419     if (aResult.get()) {
1420       aGeomShape = aResult->shape();
1421     }
1422   }
1423
1424   if (aGeomShape.get()) {
1425     TopoDS_Shape aTDSShape = aGeomShape->impl<TopoDS_Shape>();
1426     return PartSet_Tools::findAttributeBy2dPoint(theObject, aTDSShape,
1427                                                  mySketchMgr->activeSketch());
1428   }
1429   return anAttribute;
1430 }
1431
1432 //******************************************************
1433 void PartSet_Module::onChoiceChanged(ModuleBase_ModelWidget* theWidget,
1434                                      int theIndex)
1435 {
1436   PartSet_WidgetChoice* aChoiceWidget = dynamic_cast<PartSet_WidgetChoice*>(theWidget);
1437   if (!aChoiceWidget)
1438     return;
1439
1440   QString aChoiceTitle = aChoiceWidget->getPropertyPanelTitle(theIndex);
1441   if (!aChoiceTitle.isEmpty()) {
1442     ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1443     if (!aOperation)
1444       return;
1445     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
1446     if (aPanel)
1447       aPanel->setWindowTitle(aChoiceTitle);
1448   }
1449 }
1450
1451 //******************************************************
1452 XGUI_Workshop* PartSet_Module::getWorkshop() const
1453 {
1454   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
1455   return aConnector->workshop();
1456 }
1457
1458 //******************************************************
1459 void PartSet_Module::setDefaultConstraintShown()
1460 {
1461   myHasConstraintShown[PartSet_Tools::Geometrical] = true;
1462   myHasConstraintShown[PartSet_Tools::Dimensional] = true;
1463   myHasConstraintShown[PartSet_Tools::Expressions] = false;
1464 }