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