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