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