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