]> SALOME platform Git repositories - modules/shaper.git/blob - src/PartSet/PartSet_Module.cpp
Salome HOME
Issue #2061 arc edit problem: correction for center of arc(last described problem)
[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_WidgetPoint2DFlyout.h"
10 #include "PartSet_WidgetShapeSelector.h"
11 #include "PartSet_WidgetMultiSelector.h"
12 #include "PartSet_WidgetSubShapeSelector.h"
13 #include "PartSet_WidgetFeaturePointSelector.h"
14 #include "PartSet_WidgetEditor.h"
15 #include "PartSet_WidgetFileSelector.h"
16 #include "PartSet_WidgetSketchCreator.h"
17 #include "PartSet_SketcherMgr.h"
18 #include "PartSet_SketcherReentrantMgr.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_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 #include <ModelAPI_Tools.h>
55 #include <ModelAPI_ResultConstruction.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 <AIS_Dimension.hxx>
94 #include <AIS_InteractiveObject.hxx>
95 #include <StdSelect_TypeOfFace.hxx>
96 #include <TopoDS_Vertex.hxx>
97 #include <TopoDS.hxx>
98 #include <TopoDS_Shape.hxx>
99 #include <BRep_Tool.hxx>
100
101 #include <QObject>
102 #include <QMouseEvent>
103 #include <QString>
104 #include <QTimer>
105 #include <QApplication>
106 #include <QMessageBox>
107 #include <QMainWindow>
108 #include <QLineEdit>
109 #include <QString>
110
111 #include <GeomAlgoAPI_FaceBuilder.h>
112 #include <GeomDataAPI_Dir.h>
113
114 #include <SelectMgr_ListIteratorOfListOfFilter.hxx>
115
116 #ifdef _DEBUG
117 #include <QDebug>
118 #endif
119
120 /*!Create and return new instance of XGUI_Module*/
121 extern "C" PARTSET_EXPORT ModuleBase_IModule* createModule(ModuleBase_IWorkshop* theWshop)
122 {
123   return new PartSet_Module(theWshop);
124 }
125
126 PartSet_Module::PartSet_Module(ModuleBase_IWorkshop* theWshop)
127 : ModuleBase_IModule(theWshop),
128   myVisualLayerId(0),
129   myIsOperationIsLaunched(false)
130 {
131   new PartSet_IconFactory();
132
133   mySketchMgr = new PartSet_SketcherMgr(this);
134   mySketchReentrantMgr = new PartSet_SketcherReentrantMgr(theWshop);
135
136   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWshop);
137   XGUI_Workshop* aWorkshop = aConnector->workshop();
138
139   ModuleBase_IViewer* aViewer = theWshop->viewer();
140   connect(aViewer, SIGNAL(keyRelease(ModuleBase_IViewWindow*, QKeyEvent*)),
141           this, SLOT(onKeyRelease(ModuleBase_IViewWindow*, QKeyEvent*)));
142   connect(aViewer, SIGNAL(viewTransformed(int)),
143           SLOT(onViewTransformed(int)));
144   connect(aViewer, SIGNAL(viewCreated(ModuleBase_IViewWindow*)),
145           SLOT(onViewCreated(ModuleBase_IViewWindow*)));
146   myMenuMgr = new PartSet_MenuMgr(this);
147   myCustomPrs = new PartSet_CustomPrs(theWshop);
148
149   myOverconstraintListener = new PartSet_OverconstraintListener(theWshop);
150
151   Events_Loop* aLoop = Events_Loop::loop();
152   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_DOCUMENT_CHANGED));
153
154   mySelectionFilters.Append(new PartSet_GlobalFilter(myWorkshop));
155   mySelectionFilters.Append(new PartSet_FilterInfinite(myWorkshop));
156
157   setDefaultConstraintShown();
158
159   Config_PropManager::registerProp("Visualization", "operation_parameter_color",
160                           "Reference shape wireframe color in operation", Config_Prop::Color,
161                           PartSet_CustomPrs::OPERATION_PARAMETER_COLOR());
162   Config_PropManager::registerProp("Visualization", "operation_result_color",
163                           "Result shape wireframe color in operation", Config_Prop::Color,
164                           PartSet_CustomPrs::OPERATION_RESULT_COLOR());
165   Config_PropManager::registerProp("Visualization", "operation_highlight_color",
166                           "Multi selector item color in operation", Config_Prop::Color,
167                           PartSet_CustomPrs::OPERATION_HIGHLIGHT_COLOR());
168   Config_PropManager::registerProp("Visualization", "operation_remove_feature_color",
169                           "Color of removed feature in operation", Config_Prop::Color,
170                           PartSet_CustomPrs::OPERATION_REMOVE_FEATURE_COLOR());
171 }
172
173 PartSet_Module::~PartSet_Module()
174 {
175   SelectMgr_ListIteratorOfListOfFilter aIt(mySelectionFilters);
176   for (; aIt.More(); aIt.Next()) {
177     Handle(SelectMgr_Filter) aFilter = aIt.Value();
178     if (!aFilter.IsNull())
179       aFilter.Nullify();
180   }
181   delete myCustomPrs;
182   delete myOverconstraintListener;
183 }
184
185 void PartSet_Module::activateSelectionFilters()
186 {
187   SelectMgr_ListIteratorOfListOfFilter aIt(mySelectionFilters);
188   for (; aIt.More(); aIt.Next()) {
189     Handle(SelectMgr_Filter) aFilter = aIt.Value();
190     if (!aFilter.IsNull())
191       myWorkshop->viewer()->addSelectionFilter(aFilter);
192   }
193 }
194
195 void PartSet_Module::deactivateSelectionFilters()
196 {
197   SelectMgr_ListIteratorOfListOfFilter aIt(mySelectionFilters);
198   for (; aIt.More(); aIt.Next()) {
199     Handle(SelectMgr_Filter) aFilter = aIt.Value();
200     if (!aFilter.IsNull())
201       myWorkshop->viewer()->removeSelectionFilter(aFilter);
202   }
203 }
204
205 void PartSet_Module::storeSelection()
206 {
207   // cash is used only to restore selection, so it should be filled in storeSelection and
208   // after applying immediatelly cleared in restoreSelection
209   myCurrentSelection.clear();
210   sketchMgr()->storeSelection(false, myCurrentSelection);
211 }
212
213 void PartSet_Module::restoreSelection()
214 {
215   // cash is used only to restore selection, so it should be filled in storeSelection and
216   // after applying immediatelly cleared in restoreSelection
217   sketchMgr()->restoreSelection(myCurrentSelection);
218   myCurrentSelection.clear();
219 }
220
221 void PartSet_Module::registerValidators()
222 {
223   //Registering of validators
224   SessionPtr aMgr = ModelAPI_Session::get();
225   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
226   aFactory->registerValidator("PartSet_DistanceSelection", new PartSet_DistanceSelection);
227   aFactory->registerValidator("PartSet_LengthSelection", new PartSet_LengthSelection);
228   aFactory->registerValidator("PartSet_PerpendicularSelection", new PartSet_PerpendicularSelection);
229   aFactory->registerValidator("PartSet_ParallelSelection", new PartSet_ParallelSelection);
230   aFactory->registerValidator("PartSet_RadiusSelection", new PartSet_RadiusSelection);
231   aFactory->registerValidator("PartSet_RigidSelection", new PartSet_RigidSelection);
232   aFactory->registerValidator("PartSet_CoincidentSelection", new PartSet_CoincidentSelection);
233   aFactory->registerValidator("PartSet_HVDirSelection", new PartSet_HVDirSelection);
234   aFactory->registerValidator("PartSet_TangentSelection", new PartSet_TangentSelection);
235   aFactory->registerValidator("PartSet_FilletSelection", new PartSet_FilletSelection);
236   aFactory->registerValidator("PartSet_AngleSelection", new PartSet_AngleSelection);
237   aFactory->registerValidator("PartSet_EqualSelection", new PartSet_EqualSelection);
238   aFactory->registerValidator("PartSet_CollinearSelection", new PartSet_CollinearSelection);
239   aFactory->registerValidator("PartSet_MiddlePointSelection", new PartSet_MiddlePointSelection);
240   aFactory->registerValidator("PartSet_DifferentObjects", new PartSet_DifferentObjectsValidator);
241   aFactory->registerValidator("PartSet_CoincidentAttr", new PartSet_CoincidentAttr);
242   aFactory->registerValidator("PartSet_MultyTranslationSelection",
243     new PartSet_MultyTranslationSelection);
244   aFactory->registerValidator("PartSet_SplitSelection", new PartSet_SplitSelection);
245   aFactory->registerValidator("PartSet_ProjectionSelection", new PartSet_ProjectionSelection);
246 }
247
248 void PartSet_Module::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget,
249                                             const bool isToConnect)
250 {
251   mySketchMgr->connectToPropertyPanel(theWidget, isToConnect);
252 }
253
254 void PartSet_Module::operationCommitted(ModuleBase_Operation* theOperation)
255 {
256   if (sketchMgr()->isNestedSketchOperation(theOperation)) {
257     mySketchMgr->commitNestedSketch(theOperation);
258   }
259
260   /// Restart sketcher operations automatically
261   if (!mySketchReentrantMgr->operationCommitted(theOperation)) {
262
263     ModuleBase_OperationFeature* aFOperation =
264       dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
265     if (aFOperation && !aFOperation->isEditOperation()) {
266       // the selection is cleared after commit the create operation
267       // in order to do not use the same selected objects in the restarted operation
268       // for common behaviour, the selection is cleared even if the operation is not restarted
269       getWorkshop()->selector()->clearSelection();
270     }
271   }
272 }
273
274 void PartSet_Module::operationAborted(ModuleBase_Operation* theOperation)
275 {
276   /// Restart sketcher operations automatically
277   mySketchReentrantMgr->operationAborted(theOperation);
278 }
279
280 void PartSet_Module::operationStarted(ModuleBase_Operation* theOperation)
281 {
282   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
283                                                                                 (theOperation);
284   if (aFOperation) {
285     XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(workshop());
286     XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
287
288     ModuleBase_ModelWidget* aFilledWidget = 0;
289     bool aPostonedWidgetActivation = false;
290
291     FeaturePtr aFeature = aFOperation->feature();
292     /// Restart sketcher operations automatically
293     /// it is important to call method of sketch reentrant manager before filling of PP
294     /// because it fills some created feature attributes, these new values should be used
295     /// to fill the property panel
296     mySketchReentrantMgr->operationStarted(theOperation);
297
298     aWorkshop->fillPropertyPanel(aFOperation);
299     // filling the operation values by the current selection
300     // if the operation can be committed after the controls filling, the method perform should
301     // be stopped. Otherwise unnecessary presentations can be shown(e.g. operation prs in sketch)
302     bool isOperationCommitted = false;
303     if (!aFOperation->isEditOperation()) {
304       std::string aGreedAttributeId = ModuleBase_Tools::findGreedAttribute(workshop(), aFeature);
305       // if there is a greed attribute, automatic commit by preselection
306       // for this feature is prohibited
307       aFilledWidget = aFOperation->activateByPreselection(aGreedAttributeId);
308       if (currentOperation() != aFOperation)
309         isOperationCommitted = true;
310       else {
311         if (aGreedAttributeId.empty()) {
312           // a signal should be emitted before the next widget activation
313           // because, the activation of the next widget will give a focus to the widget.
314           // As a result the value of the widget is initialized.
315           // And commit may happens until the value is entered.
316           if (aFilledWidget) {
317             if (mySketchReentrantMgr->canBeCommittedByPreselection())
318               isOperationCommitted = mySketchMgr->operationActivatedByPreselection();
319             // activate the next obligatory widget
320             if (!isOperationCommitted)
321               aPropertyPanel->activateNextWidget(aFilledWidget);
322           }
323         }
324         else { // there is a greed widget
325           const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
326           std::string aFirstAttributeId = aWidgets.front()->attributeID();
327           // activate next widget after greeded if it is the first widget in the panel
328           // else the first panel widget is already activated by operation start
329           if (aFirstAttributeId == aGreedAttributeId)
330             aPostonedWidgetActivation = true;
331         }
332       }
333     } if (!isOperationCommitted) {
334       aWorkshop->connectToPropertyPanel(true);
335       updateSketcherOnStart(aFOperation);
336       updatePresentationsOnStart(aFOperation);
337
338       // the objects of the current operation should be deactivated
339       QObjectPtrList anObjects;
340       anObjects.append(aFeature);
341       std::list<ResultPtr> aResults;
342       ModelAPI_Tools::allResults(aFeature, aResults);
343       std::list<ResultPtr>::const_iterator aIt;
344       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
345         anObjects.append(*aIt);
346       }
347       QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
348       for (; anIt != aLast; anIt++)
349         aWorkshop->deactivateActiveObject(*anIt, false);
350       if (anObjects.size() > 0) {
351         XGUI_Displayer* aDisplayer = aWorkshop->displayer();
352         aDisplayer->updateViewer();
353       }
354       /// state of command actions should be updated after displayed objects modification because
355       /// deactivation(for example) of objects may influence on selection in the viewer
356       /// State of command actions may depend on selection in the viewer(e.g. Sketch)
357       workshop()->updateCommandStatus();
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->isInternalEditActive())
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 void PartSet_Module::getGeomSelection(const std::shared_ptr<ModuleBase_ViewerPrs>& theSelected,
562                                       ObjectPtr& theObject, AttributePtr& theAttribute)
563 {
564   ObjectPtr anObject = theSelected->object();
565   GeomShapePtr aShape = theSelected->shape();
566
567   theAttribute = findAttribute(anObject, aShape);
568   // TODO: try to create result if object is an external object
569   theObject = anObject;
570 }
571
572 bool PartSet_Module::isMouseOverWindow()
573 {
574   return mySketchMgr->isMouseOverWindow();
575 }
576
577 bool PartSet_Module::isSketchNeutralPointActivated() const
578 {
579   bool isNeutralPoint = true;
580   if (sketchReentranceMgr()->isInternalEditActive())
581     isNeutralPoint = false;
582   if (myIsOperationIsLaunched)
583     isNeutralPoint = false;
584
585   return isNeutralPoint;
586 }
587
588 void PartSet_Module::closeDocument()
589 {
590   myActivePartIndex = QModelIndex();
591   clearViewer();
592 }
593
594 void PartSet_Module::clearViewer()
595 {
596   myCustomPrs->clearPrs();
597
598   XGUI_Workshop* aWorkshop = getWorkshop();
599   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
600   aDisplayer->deactivateSelectionFilters();
601 }
602
603 void PartSet_Module::propertyPanelDefined(ModuleBase_Operation* theOperation)
604 {
605   ModuleBase_OperationFeature* aFOperation =
606     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
607   if (!aFOperation)
608     return;
609
610   ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
611   // we have to manually activate the sketch label in edit mode
612   if (PartSet_SketcherMgr::isSketchOperation(aFOperation) &&  (aFOperation->isEditOperation()))
613     aPanel->activateWidget(aPanel->modelWidgets().first());
614 }
615
616 bool PartSet_Module::createWidgets(ModuleBase_Operation* theOperation,
617                                    QList<ModuleBase_ModelWidget*>& theWidgets) const
618 {
619   bool aProcessed = false;
620
621   ModuleBase_OperationFeature* aFOperation =
622     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
623   XGUI_Workshop* aWorkshop = getWorkshop();
624   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
625   if (mySketchMgr->activeSketch().get() && aFOperation && aPropertyPanel) {
626     ModuleBase_ISelection* aSelection = workshop()->selection();
627     // click on a point in sketch leads here with the point is highlighted, not yet selected
628     QList<ModuleBase_ViewerPrsPtr> aPreselection = aSelection->getHighlighted();
629     if (aPreselection.size() == 1) {
630       ModuleBase_ViewerPrsPtr aSelectedPrs = aPreselection[0];
631       ObjectPtr anObject = aSelectedPrs->object();
632
633       FeaturePtr aFeature = ModelAPI_Feature::feature(anObject);
634       FeaturePtr anOpFeature = aFOperation->feature();
635       GeomShapePtr aShape = aSelectedPrs->shape();
636       // click on the digit of dimension constrain comes here
637       // with an empty shape, so we need the check
638       if (aFeature == anOpFeature && aShape.get() && !aShape->isNull()) {
639         // if feature has only one result and shape of result is equal to selected shape
640         // this attribute is not processed. It is a case of Sketch Point.
641         if (aFeature->results().size() == 1) {
642           ResultPtr aResult = aFeature->results().front();
643           if (aResult.get() && aResult->shape()->isEqual(aShape))
644             return aProcessed;
645         }
646         const TopoDS_Shape& aTDShape = aShape->impl<TopoDS_Shape>();
647         AttributePtr anAttribute = PartSet_Tools::findAttributeBy2dPoint(anObject, aTDShape,
648                                                                mySketchMgr->activeSketch());
649         if (anAttribute.get()) {
650           QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
651           ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), workshop());
652
653           const std::string anAttributeId = anAttribute->id();
654           aFactory.createWidget(aPropertyPanel->contentWidget(), anAttributeId);
655
656           theWidgets = aFactory.getModelWidgets();
657           // it is possible that the point does not present in XML definition,
658           // in this case, we assume that it is not processed by this module
659           // e.g. "Intersection point" feature
660           aProcessed = !theWidgets.isEmpty();
661         }
662       }
663     }
664   }
665   return aProcessed;
666 }
667
668 void PartSet_Module::onSelectionChanged()
669 {
670   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
671   if (!aOperation)
672     return;
673
674   bool isSketcherOp = false;
675   // An edit operation is enable only if the current opeation is the sketch operation
676   if (mySketchMgr->activeSketch()) {
677     if (PartSet_Tools::sketchPlane(mySketchMgr->activeSketch()))
678       isSketcherOp = PartSet_SketcherMgr::isSketchOperation(aOperation);
679   }
680   if (isSketcherOp) {
681     // Editing of constraints can be done on selection
682     ModuleBase_ISelection* aSelect = myWorkshop->selection();
683     QList<ModuleBase_ViewerPrsPtr> aSelected = aSelect->getSelected();
684     if (aSelected.size() == 1) {
685       ModuleBase_ViewerPrsPtr aPrs = aSelected.first();
686       ObjectPtr aObject = aPrs->object();
687       FeaturePtr aFeature = ModelAPI_Feature::feature(aObject);
688       if (aFeature) {
689         std::string aId = aFeature->getKind();
690         if ((aId == SketchPlugin_ConstraintRadius::ID()) ||
691             (aId == SketchPlugin_ConstraintLength::ID()) ||
692             (aId == SketchPlugin_ConstraintDistance::ID()) ||
693             (aId == SketchPlugin_ConstraintAngle::ID())) {
694           editFeature(aFeature);
695         }
696       }
697     }
698   }
699 }
700
701 void PartSet_Module::onKeyRelease(ModuleBase_IViewWindow* theWnd, QKeyEvent* theEvent)
702 {
703   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
704   XGUI_OperationMgr* anOpMgr = aConnector->workshop()->operationMgr();
705   anOpMgr->onKeyReleased(theWnd->viewPort(), theEvent);
706 }
707
708 ModuleBase_ModelWidget* PartSet_Module::createWidgetByType(const std::string& theType,
709                                                            QWidget* theParent,
710                                                            Config_WidgetAPI* theWidgetApi)
711 {
712   ModuleBase_IWorkshop* aWorkshop = workshop();
713   XGUI_Workshop* aXUIWorkshop = getWorkshop();
714   ModuleBase_ModelWidget* aWgt = NULL;
715   if (theType == "sketch-start-label") {
716     PartSet_WidgetSketchLabel* aLabelWgt = new PartSet_WidgetSketchLabel(theParent, aWorkshop,
717                                                                theWidgetApi, myHasConstraintShown);
718     connect(aLabelWgt, SIGNAL(planeSelected(const std::shared_ptr<GeomAPI_Pln>&)),
719       mySketchMgr, SLOT(onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>&)));
720     connect(aLabelWgt, SIGNAL(showConstraintToggled(int, bool)),
721       mySketchMgr, SLOT(onShowConstraintsToggle(int, bool)));
722     aWgt = aLabelWgt;
723   } else if (theType == "sketch-2dpoint_selector") {
724     PartSet_WidgetPoint2D* aPointWgt = new PartSet_WidgetPoint2D(theParent, aWorkshop,
725                                                                  theWidgetApi);
726     aPointWgt->setSketch(mySketchMgr->activeSketch());
727     connect(aPointWgt, SIGNAL(vertexSelected()), sketchReentranceMgr(), SLOT(onVertexSelected()));
728     aWgt = aPointWgt;
729   }else if (theType == "sketch-2dpoint_flyout_selector") {
730     PartSet_WidgetPoint2DFlyout* aPointWgt = new PartSet_WidgetPoint2DFlyout(theParent, aWorkshop,
731                                                                              theWidgetApi);
732     aPointWgt->setSketch(mySketchMgr->activeSketch());
733     connect(aPointWgt, SIGNAL(vertexSelected()), sketchReentranceMgr(), SLOT(onVertexSelected()));
734     aWgt = aPointWgt;
735   } else if (theType == "sketch_shape_selector") {
736     PartSet_WidgetShapeSelector* aShapeSelectorWgt =
737                           new PartSet_WidgetShapeSelector(theParent, aWorkshop, theWidgetApi);
738     aShapeSelectorWgt->setSketcher(mySketchMgr->activeSketch());
739     aWgt = aShapeSelectorWgt;
740   } else if (theType == "sketch_multi_selector") {
741     PartSet_WidgetMultiSelector* aShapeSelectorWgt =
742                           new PartSet_WidgetMultiSelector(theParent, aWorkshop, theWidgetApi);
743     aShapeSelectorWgt->setSketcher(mySketchMgr->activeSketch());
744     aWgt = aShapeSelectorWgt;
745   }
746   else if (theType == "sketch_sub_shape_selector") {
747     PartSet_WidgetSubShapeSelector* aSubShapeSelectorWgt =
748                           new PartSet_WidgetSubShapeSelector(theParent, aWorkshop, theWidgetApi);
749     aSubShapeSelectorWgt->setSketcher(mySketchMgr->activeSketch());
750     aWgt = aSubShapeSelectorWgt;
751   }
752   else if (theType == "sketch_feature_point_selector") {
753     PartSet_WidgetFeaturePointSelector* aPointSelectorWgt =
754             new PartSet_WidgetFeaturePointSelector(theParent, aWorkshop, theWidgetApi);
755     aPointSelectorWgt->setSketcher(mySketchMgr->activeSketch());
756     aWgt = aPointSelectorWgt;
757   }
758   else if (theType == WDG_DOUBLEVALUE_EDITOR) {
759     aWgt = new PartSet_WidgetEditor(theParent, aWorkshop, theWidgetApi);
760   } else if (theType == "export_file_selector") {
761     aWgt = new PartSet_WidgetFileSelector(theParent, aWorkshop, theWidgetApi);
762   } else if (theType == "sketch_launcher") {
763     aWgt = new PartSet_WidgetSketchCreator(theParent, this, theWidgetApi);
764   } else if (theType == "module_choice") {
765     aWgt = new PartSet_WidgetChoice(theParent, theWidgetApi);
766     connect(aWgt, SIGNAL(itemSelected(ModuleBase_ModelWidget*, int)),
767             this, SLOT(onChoiceChanged(ModuleBase_ModelWidget*, int)));
768   }
769   return aWgt;
770 }
771
772 ModuleBase_ModelWidget* PartSet_Module::activeWidget() const
773 {
774   ModuleBase_ModelWidget* anActiveWidget = 0;
775
776   anActiveWidget = mySketchReentrantMgr->internalActiveWidget();
777   if (!anActiveWidget) {
778     ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
779     if (aOperation) {
780       ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
781       anActiveWidget = aPanel ? aPanel->activeWidget() : 0;
782     }
783   }
784   return anActiveWidget;
785 }
786
787 bool PartSet_Module::deleteObjects()
788 {
789   bool isProcessed = false;
790
791   XGUI_Workshop* aWorkshop = getWorkshop();
792   XGUI_OperationMgr* anOpMgr = aWorkshop->operationMgr();
793
794   //SessionPtr aMgr = ModelAPI_Session::get();
795   // 1. check whether the delete should be processed in the module
796   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
797   bool isSketchOp = PartSet_SketcherMgr::isSketchOperation(anOperation),
798        isNestedOp = sketchMgr()->isNestedSketchOperation(anOperation);
799   if (isSketchOp || isNestedOp) {
800     isProcessed = true;
801     // 2. find selected presentations
802     // selected objects should be collected before the current operation abort because
803     // the abort leads to selection lost on constraint objects. It can be corrected after #386 issue
804     ModuleBase_ISelection* aSel = workshop()->selection();
805     QObjectPtrList aSelectedObj = aSel->selectedPresentations();
806     // if there are no selected objects in the viewer, that means that the selection in another
807     // place cased this method. It is necessary to return the false value to understande in above
808     // method that delete is not processed
809     if (aSelectedObj.count() == 0)
810       return false;
811
812     // avoid delete of the objects, which are not belong to the current sketch
813     // in order to do not delete results of other sketches
814     QObjectPtrList aSketchObjects;
815     QObjectPtrList::const_iterator anIt = aSelectedObj.begin(), aLast = aSelectedObj.end();
816     for ( ; anIt != aLast; anIt++) {
817       ObjectPtr anObject = *anIt;
818       if (mySketchMgr->isObjectOfSketch(anObject)) {
819         // sketch feature should be used in this list because workshop deletes features only
820         // results are skipped
821         FeaturePtr aSketchFeature = ModelAPI_Feature::feature(anObject);
822         aSketchObjects.append(aSketchFeature);
823       }
824     }
825     // if the selection contains only local selected presentations from other sketches,
826     // the Delete operation should not be done at all
827     if (aSketchObjects.size() == 0)
828       return true;
829
830     // 3. start operation
831     QString aDescription = aWorkshop->contextMenuMgr()->action("DELETE_CMD")->text();
832     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, this);
833
834     // the active nested sketch operation should be aborted unconditionally
835     // the Delete action should be additionally granted for the Sketch operation
836     // in order to do not abort/commit it
837     bool isCommitted;
838     if (!anOpMgr->canStartOperation(anOpAction->id(), isCommitted))
839       return true; // the objects are processed but can not be deleted
840
841     anOpMgr->startOperation(anOpAction);
842
843     // WORKAROUND, should be done to avoid viewer highlight update after deletetion of objects
844     // the problem is in AIS Dimensions recompute
845     // if a line and the dim are removed, line is the first
846     // it causes the AIS recompute, where the base line is null,
847     // the result is empty AIS in the viewer
848     XGUI_Tools::workshop(myWorkshop)->selector()->clearSelection();
849
850     // 4. delete features
851     // sketch feature should be skipped, only sub-features can be removed
852     // when sketch operation is active
853     aWorkshop->deleteFeatures(aSketchObjects);
854     // 5. stop operation
855     anOpMgr->commitOperation();
856   }
857   return isProcessed;
858 }
859
860 void PartSet_Module::editFeature(FeaturePtr theFeature)
861 {
862   storeConstraintsState(theFeature->getKind());
863   ModuleBase_IModule::editFeature(theFeature);
864 }
865
866 bool PartSet_Module::canCommitOperation() const
867 {
868   return true;
869 }
870
871 void PartSet_Module::launchOperation(const QString& theCmdId, const bool& isStartAfterCommitOnly)
872 {
873   myIsOperationIsLaunched = true;
874   storeConstraintsState(theCmdId.toStdString());
875   updateConstraintsState(theCmdId.toStdString());
876
877   ModuleBase_IModule::launchOperation(theCmdId, isStartAfterCommitOnly);
878
879   myIsOperationIsLaunched = false;
880 }
881
882 void PartSet_Module::storeConstraintsState(const std::string& theFeatureKind)
883 {
884   if (myWorkshop->currentOperation() &&
885       myWorkshop->currentOperation()->id().toStdString() == SketchPlugin_Sketch::ID()) {
886     const QMap<PartSet_Tools::ConstraintVisibleState, bool>& aShownStates =
887                                                   mySketchMgr->showConstraintStates();
888     myHasConstraintShown = aShownStates;
889   }
890 }
891
892 void PartSet_Module::updateConstraintsState(const std::string& theFeatureKind)
893 {
894   if (PartSet_SketcherMgr::constraintsIdList().contains(theFeatureKind.c_str()) ||
895       PartSet_SketcherMgr::replicationsIdList().contains(theFeatureKind.c_str())) {
896     // Show constraints if a constraint was anOperation
897     mySketchMgr->updateBySketchParameters(PartSet_Tools::Geometrical, true);
898     mySketchMgr->updateBySketchParameters(PartSet_Tools::Dimensional, true);
899     mySketchMgr->updateBySketchParameters(PartSet_Tools::Expressions,
900                                           myHasConstraintShown[PartSet_Tools::Expressions]);
901   }
902 }
903
904 void PartSet_Module::onObjectDisplayed(ObjectPtr theObject, AISObjectPtr theAIS)
905 {
906   Handle(AIS_InteractiveObject) anAIS = theAIS->impl<Handle(AIS_InteractiveObject)>();
907   if (!anAIS.IsNull()) {
908     Handle(AIS_InteractiveContext) aCtx = anAIS->GetContext();
909     Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(anAIS);
910     if (!aDim.IsNull()) {
911       aCtx->SetZLayer(aDim, myVisualLayerId);
912     } else {
913       Handle(SketcherPrs_SymbolPrs) aCons = Handle(SketcherPrs_SymbolPrs)::DownCast(anAIS);
914       if (!aCons.IsNull())
915         aCtx->SetZLayer(aCons, myVisualLayerId);
916     }
917   }
918 }
919
920 void PartSet_Module::onBeforeObjectErase(ObjectPtr theObject, AISObjectPtr theAIS)
921 {
922   // this is obsolete
923   // it should be recomputed in order to disappear in the viewer if the corresponded object
924   // is erased
925   //if (myCustomPrs->isActive())
926   //  myCustomPrs->redisplay(theObject, false);
927 }
928
929 void PartSet_Module::onViewTransformed(int theTrsfType)
930 {
931   // Set length of arrows constant in pixel size
932   // if the operation is panning or rotate or panglobal then do nothing
933   if ((theTrsfType == 1) || (theTrsfType == 3) || (theTrsfType == 4))
934     return;
935   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
936   Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
937   if (aContext.IsNull())
938     return;
939
940   //Handle(V3d_View) aView = aViewer->activeView();
941
942   XGUI_Workshop* aWorkshop = getWorkshop();
943   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
944   Handle(V3d_Viewer) aV3dViewer = aContext->CurrentViewer();
945   Handle(V3d_View) aView;
946   double aScale = 0;
947   for (aV3dViewer->InitDefinedViews();
948        aV3dViewer->MoreDefinedViews();
949        aV3dViewer->NextDefinedViews()) {
950     Handle(V3d_View) aV = aV3dViewer->DefinedView();
951     double aS = aV->Scale();
952     if (aS > aScale) {
953       aScale = aS;
954       aView = aV;
955     }
956   }
957   if (aView.IsNull())
958     return;
959   double aLen = aView->Convert(SketcherPrs_Tools::getDefaultArrowSize());
960
961   double aPrevLen = SketcherPrs_Tools::getArrowSize();
962   SketcherPrs_Tools::setArrowSize(aLen);
963   const double aPrevScale = aViewer->Scale(aViewer->activeView());
964   const double aCurScale = aViewer->activeView()->Camera()->Scale();
965   aViewer->SetScale(aViewer->activeView(), aCurScale);
966   SketcherPrs_Tools::setTextHeight (aCurScale / aPrevScale * SketcherPrs_Tools::getTextHeight());
967   bool isModified = false;
968   QList<AISObjectPtr> aPrsList = aDisplayer->displayedPresentations();
969   foreach (AISObjectPtr aAIS, aPrsList) {
970     Handle(AIS_InteractiveObject) aAisObj = aAIS->impl<Handle(AIS_InteractiveObject)>();
971
972     Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(aAisObj);
973     if (!aDim.IsNull()) {
974       aDim->DimensionAspect()->ArrowAspect()->SetLength(aLen);
975       aContext->Redisplay(aDim, false);
976       isModified = true;
977     }
978   }
979   if (isModified)
980     aDisplayer->updateViewer();
981 }
982
983 bool PartSet_Module::isCustomPrsActivated(const ModuleBase_CustomizeFlag& theFlag) const
984 {
985   return myCustomPrs->isActive(theFlag);
986 }
987
988 void PartSet_Module::activateCustomPrs(const FeaturePtr& theFeature,
989                                        const ModuleBase_CustomizeFlag& theFlag,
990                                        const bool theUpdateViewer)
991 {
992   myCustomPrs->activate(theFeature, theFlag, theUpdateViewer);
993 }
994
995 void PartSet_Module::deactivateCustomPrs(const ModuleBase_CustomizeFlag& theFlag,
996                                          const bool theUpdateViewer)
997 {
998   myCustomPrs->deactivate(theFlag, theUpdateViewer);
999 }
1000
1001 bool PartSet_Module::customisePresentation(ResultPtr theResult, AISObjectPtr thePrs,
1002                                            std::shared_ptr<GeomAPI_ICustomPrs> theCustomPrs)
1003 {
1004   bool aCustomized = false;
1005
1006   XGUI_Workshop* aWorkshop = getWorkshop();
1007   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1008   ObjectPtr anObject = aDisplayer->getObject(thePrs);
1009   if (!anObject)
1010     return aCustomized;
1011
1012   if (!theResult.get()) {
1013     std::vector<int> aColor;
1014     XGUI_CustomPrs::getDefaultColor(anObject, true, aColor);
1015     if (!aColor.empty()) {
1016       aCustomized = thePrs->setColor(aColor[0], aColor[1], aColor[2]);
1017     }
1018   }
1019   // customize dimentional constrains
1020   sketchMgr()->customizePresentation(anObject);
1021
1022   return aCustomized;
1023 }
1024
1025 bool PartSet_Module::afterCustomisePresentation(std::shared_ptr<ModelAPI_Result> theResult,
1026                                                 AISObjectPtr thePrs,
1027                                                 GeomCustomPrsPtr theCustomPrs)
1028 {
1029   bool aCustomized = false;
1030
1031   XGUI_Workshop* aWorkshop = getWorkshop();
1032   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1033   ObjectPtr anObject = aDisplayer->getObject(thePrs);
1034   if (!anObject)
1035     return aCustomized;
1036
1037   std::vector<int> aColor;
1038   bool aUseCustomColor = true;
1039   if (aUseCustomColor)
1040     myOverconstraintListener->getCustomColor(anObject, aColor);
1041   // customize sketch symbol presentation
1042   Handle(AIS_InteractiveObject) anAISIO = thePrs->impl<Handle(AIS_InteractiveObject)>();
1043   if (!anAISIO.IsNull()) {
1044     if (!Handle(SketcherPrs_SymbolPrs)::DownCast(anAISIO).IsNull()) {
1045       Handle(SketcherPrs_SymbolPrs) aPrs = Handle(SketcherPrs_SymbolPrs)::DownCast(anAISIO);
1046       if (!aPrs.IsNull()) {
1047         aPrs->SetCustomColor(aColor);
1048         aCustomized = true;
1049       }
1050     } else if (!Handle(SketcherPrs_Coincident)::DownCast(anAISIO).IsNull()) {
1051       Handle(SketcherPrs_Coincident) aPrs = Handle(SketcherPrs_Coincident)::DownCast(anAISIO);
1052       if (!aPrs.IsNull()) {
1053         aPrs->SetCustomColor(aColor);
1054         aCustomized = true;
1055       }
1056     }
1057   }
1058   // customize sketch dimension constraint presentation
1059   if (!aCustomized) {
1060     if (!aColor.empty()) { // otherwise presentation has the default color
1061       aCustomized = thePrs->setColor(aColor[0], aColor[1], aColor[2]);
1062     }
1063   }
1064   return aCustomized;
1065 }
1066
1067 bool PartSet_Module::customizeObject(ObjectPtr theObject, const ModuleBase_CustomizeFlag& theFlag,
1068                                      const bool theUpdateViewer)
1069 {
1070   bool isRedisplayed = false;
1071   if (myCustomPrs->isActive(theFlag))
1072     isRedisplayed = myCustomPrs->redisplay(theObject, theFlag, theUpdateViewer);
1073
1074   return isRedisplayed;
1075 }
1076
1077 void PartSet_Module::customizeObjectBrowser(QWidget* theObjectBrowser)
1078 {
1079   XGUI_ObjectsBrowser* aOB = dynamic_cast<XGUI_ObjectsBrowser*>(theObjectBrowser);
1080   if (aOB) {
1081     QLabel* aLabel = aOB->activeDocLabel();
1082     aLabel->installEventFilter(myMenuMgr);
1083     connect(aLabel, SIGNAL(customContextMenuRequested(const QPoint&)),
1084           SLOT(onActiveDocPopup(const QPoint&)));
1085     aOB->treeView()->setExpandsOnDoubleClick(false);
1086     connect(aOB->treeView(), SIGNAL(doubleClicked(const QModelIndex&)),
1087       SLOT(onTreeViewDoubleClick(const QModelIndex&)));
1088
1089     Events_Loop* aLoop = Events_Loop::loop();
1090     aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1091   }
1092 }
1093
1094 void PartSet_Module::onActiveDocPopup(const QPoint& thePnt)
1095 {
1096   SessionPtr aMgr = ModelAPI_Session::get();
1097   QAction* aActivatePartAction = myMenuMgr->action("ACTIVATE_PARTSET_CMD");
1098
1099   XGUI_Workshop* aWorkshop = getWorkshop();
1100   QLabel* aHeader = aWorkshop->objectBrowser()->activeDocLabel();
1101
1102   aActivatePartAction->setEnabled((aMgr->activeDocument() != aMgr->moduleDocument()));
1103
1104   QMenu aMenu;
1105   aMenu.addAction(aActivatePartAction);
1106   aMenu.exec(aHeader->mapToGlobal(thePnt));
1107 }
1108
1109 Handle(AIS_InteractiveObject) PartSet_Module::createPresentation(const ResultPtr& theResult)
1110 {
1111   return mySketchMgr->createPresentation(theResult);
1112 }
1113
1114
1115 ObjectPtr PartSet_Module::findPresentedObject(const AISObjectPtr& theAIS) const
1116 {
1117   ObjectPtr anObject;
1118   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1119   if (aOperation) {
1120     /// If last line finished on vertex the lines creation sequence has to be break
1121     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
1122     if (aPanel) {
1123       ModuleBase_ModelWidget* anActiveWidget = aPanel->activeWidget();
1124       // if there is an active widget, find the presented object in it
1125       if (!anActiveWidget)
1126         anActiveWidget = aPanel->preselectionWidget();
1127
1128       ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
1129                                                                              (anActiveWidget);
1130       if (aWidgetValidated)
1131         anObject = aWidgetValidated->findPresentedObject(theAIS);
1132     }
1133   }
1134   return anObject;
1135 }
1136
1137 bool PartSet_Module::canBeShaded(Handle(AIS_InteractiveObject) theAIS) const
1138 {
1139   bool aCanBeShaged = true;
1140
1141   Handle(PartSet_ResultSketchPrs) aPrs = Handle(PartSet_ResultSketchPrs)::DownCast(theAIS);
1142   if (!aPrs.IsNull())
1143     aCanBeShaged = false;
1144
1145   return aCanBeShaged;
1146 }
1147
1148 void PartSet_Module::addObjectBrowserMenu(QMenu* theMenu) const
1149 {
1150   QObjectPtrList aObjects = myWorkshop->selection()->selectedObjects();
1151   int aSelected = aObjects.size();
1152   SessionPtr aMgr = ModelAPI_Session::get();
1153   QAction* aActivatePartAction = myMenuMgr->action("ACTIVATE_PART_CMD");
1154
1155   bool hasResult = false;
1156   bool hasFeature = false;
1157   bool hasParameter = false;
1158   bool hasCompositeOwner = false;
1159   bool hasResultInHistory = false;
1160   ModuleBase_Tools::checkObjects(aObjects, hasResult, hasFeature, hasParameter,
1161                                   hasCompositeOwner, hasResultInHistory);
1162
1163   ModuleBase_Operation* aCurrentOp = myWorkshop->currentOperation();
1164   if (aSelected == 1) {
1165     ObjectPtr aObject = aObjects.first();
1166     if (aObject) {
1167       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1168       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1169       bool isPart = aPart.get() ||
1170         (aFeature.get() && (aFeature->getKind() == PartSetPlugin_Part::ID()));
1171       if (isPart) {
1172         DocumentPtr aPartDoc;
1173         if (!aPart.get()) {
1174           aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFeature->firstResult());
1175         }
1176         if (aPart.get()) // this may be null is Part feature is disabled
1177           aPartDoc = aPart->partDoc();
1178
1179         theMenu->addAction(aActivatePartAction);
1180         aActivatePartAction->setEnabled((aMgr->activeDocument() != aPartDoc));
1181
1182       } else if (aObject->document() == aMgr->activeDocument()) {
1183         if (hasParameter || hasFeature) {
1184           myMenuMgr->action("EDIT_CMD")->setEnabled(true);
1185           theMenu->addAction(myMenuMgr->action("EDIT_CMD"));
1186           if (aCurrentOp && aFeature.get()) {
1187             if (aCurrentOp->id().toStdString() == aFeature->getKind())
1188               myMenuMgr->action("EDIT_CMD")->setEnabled(false);
1189           }
1190         }
1191       }
1192     }
1193   } else {
1194     if (hasFeature) {
1195       myMenuMgr->action("EDIT_CMD")->setEnabled(aCurrentOp == 0);
1196       theMenu->addAction(myMenuMgr->action("EDIT_CMD"));
1197       theMenu->addSeparator();
1198     }
1199   }
1200   bool aNotDeactivate = (aCurrentOp == 0);
1201   if (!aNotDeactivate) {
1202     aActivatePartAction->setEnabled(false);
1203   }
1204 }
1205
1206 #define EXPAND_PARENT(OBJ) \
1207 QModelIndex aObjIndex = aDataModel->objectIndex(OBJ); \
1208 if (aObjIndex.isValid()) { \
1209   QModelIndex aParent = aObjIndex.parent(); \
1210   int aCount = aDataModel->rowCount(aParent); \
1211   if (aCount == 1) \
1212     aTreeView->setExpanded(aParent, true); \
1213 }
1214
1215
1216 void PartSet_Module::processEvent(const std::shared_ptr<Events_Message>& theMessage)
1217 {
1218   if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_DOCUMENT_CHANGED)) {
1219     // Do not change activation of parts if an operation active
1220     static QStringList aAllowActivationList;
1221     if (aAllowActivationList.isEmpty())
1222       aAllowActivationList <<
1223       QString(PartSetPlugin_Part::ID().c_str()) <<
1224       QString(PartSetPlugin_Duplicate::ID().c_str()) <<
1225       QString(PartSetPlugin_Remove::ID().c_str());
1226     if (myWorkshop->currentOperation() &&
1227       (!aAllowActivationList.contains(myWorkshop->currentOperation()->id())))
1228       return;
1229     XGUI_Workshop* aWorkshop = getWorkshop();
1230     XGUI_DataTree* aTreeView = aWorkshop->objectBrowser()->treeView();
1231     QLabel* aLabel = aWorkshop->objectBrowser()->activeDocLabel();
1232     QPalette aPalet = aLabel->palette();
1233
1234     SessionPtr aMgr = ModelAPI_Session::get();
1235     DocumentPtr aActiveDoc = aMgr->activeDocument();
1236     if (myActivePartIndex.isValid())
1237       aTreeView->setExpanded(myActivePartIndex, false);
1238     XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1239     myActivePartIndex = aDataModel->documentRootIndex(aActiveDoc);
1240     if (myActivePartIndex.isValid())
1241       aTreeView->setExpanded(myActivePartIndex, true);
1242
1243     aLabel->setPalette(aPalet);
1244     aWorkshop->updateCommandStatus();
1245
1246     // Update displayed objects in order to update active color
1247     XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1248     QObjectPtrList aObjects = aDisplayer->displayedObjects();
1249     bool aHidden;
1250     foreach(ObjectPtr aObj, aObjects) {
1251       aHidden = !aObj->data() || !aObj->data()->isValid() ||
1252         aObj->isDisabled() || (!aObj->isDisplayed());
1253       if (!aHidden)
1254         aDisplayer->redisplay(aObj, false);
1255     }
1256     aDisplayer->updateViewer();
1257   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
1258     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
1259         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
1260     std::set<ObjectPtr> aObjects = aUpdMsg->objects();
1261
1262     ObjectPtr aConstrObj;
1263     ObjectPtr aResultObj;
1264     std::set<ObjectPtr>::const_iterator aIt;
1265     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
1266     for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
1267       ObjectPtr aObject = (*aIt);
1268       if ((!aResultObj.get()) && (aObject->groupName() == ModelAPI_ResultBody::group())
1269           && (aObject->document() != aRootDoc))
1270         aResultObj = aObject;
1271       if ((!aConstrObj.get()) && (aObject->groupName() == ModelAPI_ResultConstruction::group())
1272           && (aObject->document() != aRootDoc))
1273         aConstrObj = aObject;
1274       if (aResultObj.get() && aConstrObj.get())
1275         break;
1276     }
1277
1278     if (aResultObj.get() || aConstrObj.get()) {
1279       XGUI_Workshop* aWorkshop = getWorkshop();
1280       XGUI_DataTree* aTreeView = aWorkshop->objectBrowser()->treeView();
1281       XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1282
1283       if (aResultObj.get()) {
1284         EXPAND_PARENT(aResultObj)
1285       }
1286       if (aConstrObj.get()) {
1287         EXPAND_PARENT(aConstrObj)
1288       }
1289     }
1290   }
1291 }
1292
1293 void PartSet_Module::onTreeViewDoubleClick(const QModelIndex& theIndex)
1294 {
1295   if (myWorkshop->currentOperation()) // Do not change activation of parts if an operation active
1296     return;
1297   SessionPtr aMgr = ModelAPI_Session::get();
1298   if (!theIndex.isValid()) {
1299     // It seems that this code is obsolete
1300     //aMgr->setActiveDocument(aMgr->moduleDocument());
1301     return;
1302   }
1303   if (theIndex.column() != 0) // Use only first column
1304     return;
1305
1306   XGUI_Workshop* aWorkshop = getWorkshop();
1307   XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1308   // De not use non editable Indexes
1309   if ((aDataModel->flags(theIndex) & Qt::ItemIsSelectable) == 0)
1310     return;
1311   ObjectPtr aObj = aDataModel->object(theIndex);
1312
1313   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1314   if (!aPart.get()) { // Probably this is Feature
1315     FeaturePtr aPartFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
1316     if (aPartFeature.get() && (aPartFeature->getKind() == PartSetPlugin_Part::ID())) {
1317       aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aPartFeature->firstResult());
1318     }
1319   }
1320   if (aPart.get()) { // if this is a part
1321     if (aPart->partDoc() == aMgr->activeDocument()) {
1322       myMenuMgr->activatePartSet();
1323     } else {
1324       myMenuMgr->activatePart(aPart);
1325     }
1326   }
1327 }
1328
1329
1330 void PartSet_Module::onViewCreated(ModuleBase_IViewWindow*)
1331 {
1332   // z layer is created for all started operations in order to visualize operation AIS presentation
1333   // over the object
1334   Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
1335   if (aContext.IsNull())
1336     return;
1337
1338   Handle(V3d_Viewer) aViewer = aContext->CurrentViewer();
1339   if (myVisualLayerId == 0) {
1340     if (myVisualLayerId == 0)
1341       aViewer->AddZLayer(myVisualLayerId);
1342   } else {
1343     TColStd_SequenceOfInteger aZList;
1344     aViewer->GetAllZLayers(aZList);
1345     bool aFound = false;
1346     for (int i = 1; i <= aZList.Length(); i++) {
1347       if (aZList(i) == myVisualLayerId) {
1348         aFound = true;
1349         break;
1350       }
1351     }
1352     if (!aFound)
1353       aViewer->AddZLayer(myVisualLayerId);
1354   }
1355   // if there is an active operation with validated widget,
1356   // the filters of this widget should be activated in the created view
1357   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1358   if (aOperation) {
1359     ModuleBase_ModelWidget* anActiveWidget = activeWidget();
1360     if (anActiveWidget) {
1361       ModuleBase_WidgetSelector* aWSelector =
1362         dynamic_cast<ModuleBase_WidgetSelector*>(anActiveWidget);
1363       if (aWSelector)
1364         aWSelector->activateSelectionAndFilters(true);
1365     }
1366   }
1367 }
1368
1369 //******************************************************
1370 void PartSet_Module::widgetStateChanged(int thePreviousState)
1371 {
1372   mySketchMgr->widgetStateChanged(thePreviousState);
1373 }
1374
1375 bool PartSet_Module::processEnter(const std::string& thePreviousAttributeID)
1376 {
1377   return mySketchReentrantMgr->processEnter(thePreviousAttributeID);
1378 }
1379
1380 //******************************************************
1381 void PartSet_Module::beforeOperationStopped(ModuleBase_Operation* theOperation)
1382 {
1383   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
1384     mySketchMgr->stopSketch(theOperation);
1385   }
1386 }
1387
1388 //******************************************************
1389 GeomShapePtr PartSet_Module::findShape(const AttributePtr& theAttribute)
1390 {
1391   GeomShapePtr aGeomShape;
1392
1393   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
1394   if (anOperation && sketchMgr()->isNestedSketchOperation(anOperation)) {
1395     aGeomShape = PartSet_Tools::findShapeBy2DPoint(theAttribute, myWorkshop);
1396   }
1397   return aGeomShape;
1398 }
1399
1400 //******************************************************
1401 AttributePtr PartSet_Module::findAttribute(const ObjectPtr& theObject,
1402                                            const GeomShapePtr& theGeomShape)
1403 {
1404   AttributePtr anAttribute;
1405   GeomShapePtr aGeomShape = theGeomShape;
1406   if (!aGeomShape.get()) {
1407     // processing shape of result, e.g. sketch circle center is selected, this is a result
1408     // the geom shape is empty, the shape of result should be used
1409     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1410     if (aResult.get()) {
1411       aGeomShape = aResult->shape();
1412     }
1413   }
1414
1415   if (aGeomShape.get()) {
1416     TopoDS_Shape aTDSShape = aGeomShape->impl<TopoDS_Shape>();
1417     return PartSet_Tools::findAttributeBy2dPoint(theObject, aTDSShape,
1418                                                  mySketchMgr->activeSketch());
1419   }
1420   return anAttribute;
1421 }
1422
1423 //******************************************************
1424 std::shared_ptr<Events_Message> PartSet_Module::reentrantMessage()
1425 {
1426   return sketchReentranceMgr()->reentrantMessage();
1427 }
1428
1429 //******************************************************
1430 void PartSet_Module::setReentrantPreSelection(const std::shared_ptr<Events_Message>& theMessage)
1431 {
1432   sketchReentranceMgr()->setReentrantPreSelection(theMessage);
1433 }
1434
1435 //******************************************************
1436 void PartSet_Module::onChoiceChanged(ModuleBase_ModelWidget* theWidget,
1437                                      int theIndex)
1438 {
1439   PartSet_WidgetChoice* aChoiceWidget = dynamic_cast<PartSet_WidgetChoice*>(theWidget);
1440   if (!aChoiceWidget)
1441     return;
1442
1443   QString aChoiceTitle = aChoiceWidget->getPropertyPanelTitle(theIndex);
1444   if (!aChoiceTitle.isEmpty()) {
1445     ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1446     if (!aOperation)
1447       return;
1448     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
1449     if (aPanel)
1450       aPanel->setWindowTitle(aChoiceTitle);
1451   }
1452 }
1453
1454 //******************************************************
1455 XGUI_Workshop* PartSet_Module::getWorkshop() const
1456 {
1457   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
1458   return aConnector->workshop();
1459 }
1460
1461 //******************************************************
1462 void PartSet_Module::setDefaultConstraintShown()
1463 {
1464   myHasConstraintShown[PartSet_Tools::Geometrical] = true;
1465   myHasConstraintShown[PartSet_Tools::Dimensional] = true;
1466   myHasConstraintShown[PartSet_Tools::Expressions] = false;
1467 }