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