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