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