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