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