Salome HOME
a9905b884dc62de59a87ab43aec89b36067f81bd
[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(PartSet_SketcherMgr::ST_SelectType, 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 bool PartSet_Module::canUsePreselection(const QString& thePreviousOperationKind,
484                                         const QString& theStartedOperationKind)
485 {
486   if (ModuleBase_IModule::canUsePreselection(thePreviousOperationKind, theStartedOperationKind))
487     return true;
488
489   return mySketchMgr->isNestedSketchFeature(theStartedOperationKind);
490 }
491
492 /*void PartSet_Module::processHiddenObject(const std::list<ObjectPtr>& theObjects)
493 {
494   mySketchMgr->processHiddenObject(theObjects);
495 }*/
496
497 bool PartSet_Module::canActivateSelection(const ObjectPtr& theObject) const
498 {
499   bool aCanActivate = ModuleBase_IModule::canActivateSelection(theObject);
500
501   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
502   bool isSketchOp = PartSet_SketcherMgr::isSketchOperation(anOperation),
503        isNestedOp = sketchMgr()->isNestedSketchOperation(anOperation);
504   if (isSketchOp || isNestedOp) {
505     // in active sketch operation it is possible to activate operation object in selection
506     // in the edit operation, e.g. points of the line can be moved when the line is edited
507     ModuleBase_OperationFeature* aFOperation =
508       dynamic_cast<ModuleBase_OperationFeature*>(anOperation);
509     aCanActivate = aCanActivate || (aFOperation && aFOperation->isEditOperation());
510   }
511   return aCanActivate;
512 }
513
514 bool PartSet_Module::addViewerMenu(const QMap<QString, QAction*>& theStdActions,
515                                    QWidget* theParent,
516                                    QMap<int, QAction*>& theMenuActions) const
517 {
518   return myMenuMgr->addViewerMenu(theStdActions, theParent, theMenuActions);
519 }
520
521 void PartSet_Module::updateViewerMenu(const QMap<QString, QAction*>& theStdActions)
522 {
523   myMenuMgr->updateViewerMenu(theStdActions);
524 }
525
526 bool PartSet_Module::isActionEnableStateFixed(const int theActionId) const
527 {
528   bool isEnabledFixed = false;
529   if (theActionId == XGUI_ActionsMgr::AcceptAll &&
530       mySketchReentrantMgr->isInternalEditActive())
531     isEnabledFixed = true;
532   return isEnabledFixed;
533 }
534
535 QString PartSet_Module::getFeatureError(const FeaturePtr& theFeature)
536 {
537   QString anError = ModuleBase_IModule::getFeatureError(theFeature);
538   if (anError.isEmpty())
539     anError = sketchMgr()->getFeatureError(theFeature);
540
541   return anError;
542 }
543
544 void PartSet_Module::grantedOperationIds(ModuleBase_Operation* theOperation,
545                                          QStringList& theIds) const
546 {
547   myMenuMgr->grantedOperationIds(theOperation, theIds);
548
549   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
550     XGUI_Workshop* aWorkshop = getWorkshop();
551     theIds.append(aWorkshop->contextMenuMgr()->action("DELETE_CMD")->text());
552   }
553 }
554
555 void PartSet_Module::activeSelectionModes(QIntList& theModes)
556 {
557   theModes.clear();
558   if (mySketchMgr->activeSketch().get())
559     PartSet_SketcherMgr::sketchSelectionModes(theModes);
560 }
561
562 void PartSet_Module::customSubShapesSelectionModes(QIntList& theTypes)
563 {
564   if (theTypes.contains(TopAbs_FACE))
565     theTypes.append(SketcherPrs_Tools::Sel_Sketch_Face);
566   if (theTypes.contains(TopAbs_WIRE))
567     theTypes.append(SketcherPrs_Tools::Sel_Sketch_Wire);
568 }
569
570 void PartSet_Module::getGeomSelection(const std::shared_ptr<ModuleBase_ViewerPrs>& theSelected,
571                                       ObjectPtr& theObject, AttributePtr& theAttribute)
572 {
573   ObjectPtr anObject = theSelected->object();
574   GeomShapePtr aShape = theSelected->shape();
575
576   theAttribute = findAttribute(anObject, aShape);
577   // TODO: try to create result if object is an external object
578   theObject = anObject;
579 }
580
581 bool PartSet_Module::isMouseOverWindow()
582 {
583   return mySketchMgr->isMouseOverWindow();
584 }
585
586 bool PartSet_Module::isSketchNeutralPointActivated() const
587 {
588   bool isNeutralPoint = true;
589   if (sketchReentranceMgr()->isInternalEditActive())
590     isNeutralPoint = false;
591   if (myIsOperationIsLaunched)
592     isNeutralPoint = false;
593
594   return isNeutralPoint;
595 }
596
597 void PartSet_Module::closeDocument()
598 {
599   myActivePartIndex = QModelIndex();
600   clearViewer();
601 }
602
603 void PartSet_Module::clearViewer()
604 {
605   myCustomPrs->clearPrs();
606
607   XGUI_Workshop* aWorkshop = getWorkshop();
608   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
609   aDisplayer->deactivateSelectionFilters();
610 }
611
612 void PartSet_Module::propertyPanelDefined(ModuleBase_Operation* theOperation)
613 {
614   ModuleBase_OperationFeature* aFOperation =
615     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
616   if (!aFOperation)
617     return;
618
619   ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
620   // we have to manually activate the sketch label in edit mode
621   if (PartSet_SketcherMgr::isSketchOperation(aFOperation) &&  (aFOperation->isEditOperation()))
622     aPanel->activateWidget(aPanel->modelWidgets().first());
623 }
624
625 bool PartSet_Module::createWidgets(ModuleBase_Operation* theOperation,
626                                    QList<ModuleBase_ModelWidget*>& theWidgets) const
627 {
628   bool aProcessed = false;
629
630   ModuleBase_OperationFeature* aFOperation =
631     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
632   XGUI_Workshop* aWorkshop = getWorkshop();
633   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
634   if (mySketchMgr->activeSketch().get() && aFOperation && aPropertyPanel) {
635     ModuleBase_ISelection* aSelection = workshop()->selection();
636     // click on a point in sketch leads here with the point is highlighted, not yet selected
637     QList<ModuleBase_ViewerPrsPtr> aPreselection = aSelection->getHighlighted();
638     if (aPreselection.size() == 1) {
639       ModuleBase_ViewerPrsPtr aSelectedPrs = aPreselection[0];
640       ObjectPtr anObject = aSelectedPrs->object();
641
642       FeaturePtr aFeature = ModelAPI_Feature::feature(anObject);
643       FeaturePtr anOpFeature = aFOperation->feature();
644       GeomShapePtr aShape = aSelectedPrs->shape();
645       // click on the digit of dimension constrain comes here
646       // with an empty shape, so we need the check
647       if (aFeature == anOpFeature && aShape.get() && !aShape->isNull()) {
648         // if feature has only one result and shape of result is equal to selected shape
649         // this attribute is not processed. It is a case of Sketch Point.
650         if (aFeature->results().size() == 1) {
651           ResultPtr aResult = aFeature->results().front();
652           if (aResult.get() && aResult->shape()->isEqual(aShape))
653             return aProcessed;
654         }
655         const TopoDS_Shape& aTDShape = aShape->impl<TopoDS_Shape>();
656         AttributePtr anAttribute = PartSet_Tools::findAttributeBy2dPoint(anObject, aTDShape,
657                                                                mySketchMgr->activeSketch());
658         if (anAttribute.get()) {
659           QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
660           ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), workshop());
661
662           const std::string anAttributeId = anAttribute->id();
663           aFactory.createWidget(aPropertyPanel->contentWidget(), anAttributeId);
664
665           theWidgets = aFactory.getModelWidgets();
666           // it is possible that the point does not present in XML definition,
667           // in this case, we assume that it is not processed by this module
668           // e.g. "Intersection point" feature
669           aProcessed = !theWidgets.isEmpty();
670         }
671       }
672     }
673   }
674   return aProcessed;
675 }
676
677 void PartSet_Module::onSelectionChanged()
678 {
679   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
680   if (!aOperation)
681     return;
682
683   bool isSketcherOp = false;
684   // An edit operation is enable only if the current opeation is the sketch operation
685   if (mySketchMgr->activeSketch()) {
686     if (PartSet_Tools::sketchPlane(mySketchMgr->activeSketch()))
687       isSketcherOp = PartSet_SketcherMgr::isSketchOperation(aOperation);
688   }
689   if (isSketcherOp) {
690     // Editing of constraints can be done on selection
691     ModuleBase_ISelection* aSelect = myWorkshop->selection();
692     QList<ModuleBase_ViewerPrsPtr> aSelected = aSelect->getSelected();
693     if (aSelected.size() == 1) {
694       ModuleBase_ViewerPrsPtr aPrs = aSelected.first();
695       ObjectPtr aObject = aPrs->object();
696       FeaturePtr aFeature = ModelAPI_Feature::feature(aObject);
697       if (aFeature) {
698         std::string aId = aFeature->getKind();
699         if ((aId == SketchPlugin_ConstraintRadius::ID()) ||
700             (aId == SketchPlugin_ConstraintLength::ID()) ||
701             (aId == SketchPlugin_ConstraintDistance::ID()) ||
702             (aId == SketchPlugin_ConstraintAngle::ID())) {
703           editFeature(aFeature);
704         }
705       }
706     }
707   }
708 }
709
710 void PartSet_Module::onKeyRelease(ModuleBase_IViewWindow* theWnd, QKeyEvent* theEvent)
711 {
712   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
713   XGUI_OperationMgr* anOpMgr = aConnector->workshop()->operationMgr();
714   anOpMgr->onKeyReleased(theWnd->viewPort(), theEvent);
715 }
716
717 ModuleBase_ModelWidget* PartSet_Module::createWidgetByType(const std::string& theType,
718                                                            QWidget* theParent,
719                                                            Config_WidgetAPI* theWidgetApi)
720 {
721   ModuleBase_IWorkshop* aWorkshop = workshop();
722   XGUI_Workshop* aXUIWorkshop = getWorkshop();
723   ModuleBase_ModelWidget* aWgt = NULL;
724   if (theType == "sketch-start-label") {
725     PartSet_WidgetSketchLabel* aLabelWgt = new PartSet_WidgetSketchLabel(theParent, aWorkshop,
726                                                                theWidgetApi, myHasConstraintShown);
727     connect(aLabelWgt, SIGNAL(planeSelected(const std::shared_ptr<GeomAPI_Pln>&)),
728       mySketchMgr, SLOT(onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>&)));
729     connect(aLabelWgt, SIGNAL(showConstraintToggled(int, bool)),
730       mySketchMgr, SLOT(onShowConstraintsToggle(int, bool)));
731     aWgt = aLabelWgt;
732   } else if (theType == "sketch-2dpoint_selector") {
733     PartSet_WidgetPoint2D* aPointWgt = new PartSet_WidgetPoint2D(theParent, aWorkshop,
734                                                                  theWidgetApi);
735     aPointWgt->setSketch(mySketchMgr->activeSketch());
736     connect(aPointWgt, SIGNAL(vertexSelected()), sketchReentranceMgr(), SLOT(onVertexSelected()));
737     aWgt = aPointWgt;
738   }else if (theType == "sketch-2dpoint_flyout_selector") {
739     PartSet_WidgetPoint2DFlyout* aPointWgt = new PartSet_WidgetPoint2DFlyout(theParent, aWorkshop,
740                                                                              theWidgetApi);
741     aPointWgt->setSketch(mySketchMgr->activeSketch());
742     connect(aPointWgt, SIGNAL(vertexSelected()), sketchReentranceMgr(), SLOT(onVertexSelected()));
743     aWgt = aPointWgt;
744   } else if (theType == "sketch_shape_selector") {
745     PartSet_WidgetShapeSelector* aShapeSelectorWgt =
746                           new PartSet_WidgetShapeSelector(theParent, aWorkshop, theWidgetApi);
747     aShapeSelectorWgt->setSketcher(mySketchMgr->activeSketch());
748     aWgt = aShapeSelectorWgt;
749   } else if (theType == "sketch_multi_selector") {
750     PartSet_WidgetMultiSelector* aShapeSelectorWgt =
751                           new PartSet_WidgetMultiSelector(theParent, aWorkshop, theWidgetApi);
752     aShapeSelectorWgt->setSketcher(mySketchMgr->activeSketch());
753     aWgt = aShapeSelectorWgt;
754   }
755   else if (theType == "sketch_sub_shape_selector") {
756     PartSet_WidgetSubShapeSelector* aSubShapeSelectorWgt =
757                           new PartSet_WidgetSubShapeSelector(theParent, aWorkshop, theWidgetApi);
758     aSubShapeSelectorWgt->setSketcher(mySketchMgr->activeSketch());
759     aWgt = aSubShapeSelectorWgt;
760   }
761   else if (theType == "sketch_feature_point_selector") {
762     PartSet_WidgetFeaturePointSelector* aPointSelectorWgt =
763             new PartSet_WidgetFeaturePointSelector(theParent, aWorkshop, theWidgetApi);
764     aPointSelectorWgt->setSketcher(mySketchMgr->activeSketch());
765     aWgt = aPointSelectorWgt;
766   }
767   else if (theType == WDG_DOUBLEVALUE_EDITOR) {
768     aWgt = new PartSet_WidgetEditor(theParent, aWorkshop, theWidgetApi);
769   } else if (theType == "export_file_selector") {
770     aWgt = new PartSet_WidgetFileSelector(theParent, aWorkshop, theWidgetApi);
771   } else if (theType == "sketch_launcher") {
772     aWgt = new PartSet_WidgetSketchCreator(theParent, this, theWidgetApi);
773   } else if (theType == "module_choice") {
774     aWgt = new PartSet_WidgetChoice(theParent, theWidgetApi);
775     connect(aWgt, SIGNAL(itemSelected(ModuleBase_ModelWidget*, int)),
776             this, SLOT(onChoiceChanged(ModuleBase_ModelWidget*, int)));
777   }
778   return aWgt;
779 }
780
781 ModuleBase_ModelWidget* PartSet_Module::activeWidget() const
782 {
783   ModuleBase_ModelWidget* anActiveWidget = 0;
784
785   anActiveWidget = mySketchReentrantMgr->internalActiveWidget();
786   if (!anActiveWidget) {
787     ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
788     if (aOperation) {
789       ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
790       anActiveWidget = aPanel ? aPanel->activeWidget() : 0;
791     }
792   }
793   return anActiveWidget;
794 }
795
796 bool PartSet_Module::deleteObjects()
797 {
798   bool isProcessed = false;
799
800   XGUI_Workshop* aWorkshop = getWorkshop();
801   XGUI_OperationMgr* anOpMgr = aWorkshop->operationMgr();
802
803   //SessionPtr aMgr = ModelAPI_Session::get();
804   // 1. check whether the delete should be processed in the module
805   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
806   bool isSketchOp = PartSet_SketcherMgr::isSketchOperation(anOperation),
807        isNestedOp = sketchMgr()->isNestedSketchOperation(anOperation);
808   if (isSketchOp || isNestedOp) {
809     isProcessed = true;
810     // 2. find selected presentations
811     // selected objects should be collected before the current operation abort because
812     // the abort leads to selection lost on constraint objects. It can be corrected after #386 issue
813     ModuleBase_ISelection* aSel = workshop()->selection();
814     QObjectPtrList aSelectedObj = aSel->selectedPresentations();
815     // if there are no selected objects in the viewer, that means that the selection in another
816     // place cased this method. It is necessary to return the false value to understande in above
817     // method that delete is not processed
818     if (aSelectedObj.count() == 0)
819       return false;
820
821     // avoid delete of the objects, which are not belong to the current sketch
822     // in order to do not delete results of other sketches
823     QObjectPtrList aSketchObjects;
824     QObjectPtrList::const_iterator anIt = aSelectedObj.begin(), aLast = aSelectedObj.end();
825     for ( ; anIt != aLast; anIt++) {
826       ObjectPtr anObject = *anIt;
827       if (mySketchMgr->isObjectOfSketch(anObject)) {
828         // sketch feature should be used in this list because workshop deletes features only
829         // results are skipped
830         FeaturePtr aSketchFeature = ModelAPI_Feature::feature(anObject);
831         aSketchObjects.append(aSketchFeature);
832       }
833     }
834     // if the selection contains only local selected presentations from other sketches,
835     // the Delete operation should not be done at all
836     if (aSketchObjects.size() == 0)
837       return true;
838
839     // 3. start operation
840     QString aDescription = aWorkshop->contextMenuMgr()->action("DELETE_CMD")->text();
841     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, this);
842
843     // the active nested sketch operation should be aborted unconditionally
844     // the Delete action should be additionally granted for the Sketch operation
845     // in order to do not abort/commit it
846     bool isCommitted;
847     if (!anOpMgr->canStartOperation(anOpAction->id(), isCommitted))
848       return true; // the objects are processed but can not be deleted
849
850     anOpMgr->startOperation(anOpAction);
851
852     // WORKAROUND, should be done to avoid viewer highlight update after deletetion of objects
853     // the problem is in AIS Dimensions recompute
854     // if a line and the dim are removed, line is the first
855     // it causes the AIS recompute, where the base line is null,
856     // the result is empty AIS in the viewer
857     XGUI_Tools::workshop(myWorkshop)->selector()->clearSelection();
858
859     // 4. delete features
860     // sketch feature should be skipped, only sub-features can be removed
861     // when sketch operation is active
862     aWorkshop->deleteFeatures(aSketchObjects);
863     // 5. stop operation
864     anOpMgr->commitOperation();
865   }
866   return isProcessed;
867 }
868
869 void PartSet_Module::editFeature(FeaturePtr theFeature)
870 {
871   storeConstraintsState(theFeature->getKind());
872   ModuleBase_IModule::editFeature(theFeature);
873 }
874
875 bool PartSet_Module::canCommitOperation() const
876 {
877   return true;
878 }
879
880 void PartSet_Module::launchOperation(const QString& theCmdId, const bool& isStartAfterCommitOnly)
881 {
882   myIsOperationIsLaunched = true;
883   storeConstraintsState(theCmdId.toStdString());
884   updateConstraintsState(theCmdId.toStdString());
885
886   ModuleBase_IModule::launchOperation(theCmdId, isStartAfterCommitOnly);
887
888   myIsOperationIsLaunched = false;
889 }
890
891 void PartSet_Module::storeConstraintsState(const std::string& theFeatureKind)
892 {
893   if (myWorkshop->currentOperation() &&
894       myWorkshop->currentOperation()->id().toStdString() == SketchPlugin_Sketch::ID()) {
895     const QMap<PartSet_Tools::ConstraintVisibleState, bool>& aShownStates =
896                                                   mySketchMgr->showConstraintStates();
897     myHasConstraintShown = aShownStates;
898   }
899 }
900
901 void PartSet_Module::updateConstraintsState(const std::string& theFeatureKind)
902 {
903   if (PartSet_SketcherMgr::constraintsIdList().contains(theFeatureKind.c_str()) ||
904       PartSet_SketcherMgr::replicationsIdList().contains(theFeatureKind.c_str())) {
905     // Show constraints if a constraint was anOperation
906     mySketchMgr->updateBySketchParameters(PartSet_Tools::Geometrical, true);
907     mySketchMgr->updateBySketchParameters(PartSet_Tools::Dimensional, true);
908     mySketchMgr->updateBySketchParameters(PartSet_Tools::Expressions,
909                                           myHasConstraintShown[PartSet_Tools::Expressions]);
910   }
911 }
912
913 void PartSet_Module::onObjectDisplayed(ObjectPtr theObject, AISObjectPtr theAIS)
914 {
915   Handle(AIS_InteractiveObject) anAIS = theAIS->impl<Handle(AIS_InteractiveObject)>();
916   if (!anAIS.IsNull()) {
917     Handle(AIS_InteractiveContext) aCtx = anAIS->GetContext();
918     Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(anAIS);
919     if (!aDim.IsNull()) {
920       aCtx->SetZLayer(aDim, myVisualLayerId);
921     } else {
922       Handle(SketcherPrs_SymbolPrs) aCons = Handle(SketcherPrs_SymbolPrs)::DownCast(anAIS);
923       if (!aCons.IsNull())
924         aCtx->SetZLayer(aCons, myVisualLayerId);
925     }
926   }
927 }
928
929 void PartSet_Module::onBeforeObjectErase(ObjectPtr theObject, AISObjectPtr theAIS)
930 {
931   // this is obsolete
932   // it should be recomputed in order to disappear in the viewer if the corresponded object
933   // is erased
934   //if (myCustomPrs->isActive())
935   //  myCustomPrs->redisplay(theObject, false);
936 }
937
938 void PartSet_Module::onViewTransformed(int theTrsfType)
939 {
940   // Set length of arrows constant in pixel size
941   // if the operation is panning or rotate or panglobal then do nothing
942   if ((theTrsfType == 1) || (theTrsfType == 3) || (theTrsfType == 4))
943     return;
944   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
945   Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
946   if (aContext.IsNull())
947     return;
948
949   //Handle(V3d_View) aView = aViewer->activeView();
950
951   XGUI_Workshop* aWorkshop = getWorkshop();
952   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
953   Handle(V3d_Viewer) aV3dViewer = aContext->CurrentViewer();
954   Handle(V3d_View) aView;
955   double aScale = 0;
956   for (aV3dViewer->InitDefinedViews();
957        aV3dViewer->MoreDefinedViews();
958        aV3dViewer->NextDefinedViews()) {
959     Handle(V3d_View) aV = aV3dViewer->DefinedView();
960     double aS = aV->Scale();
961     if (aS > aScale) {
962       aScale = aS;
963       aView = aV;
964     }
965   }
966   if (aView.IsNull())
967     return;
968   double aLen = aView->Convert(SketcherPrs_Tools::getDefaultArrowSize());
969
970   double aPrevLen = SketcherPrs_Tools::getArrowSize();
971   SketcherPrs_Tools::setArrowSize(aLen);
972   const double aPrevScale = aViewer->Scale(aViewer->activeView());
973   const double aCurScale = aViewer->activeView()->Camera()->Scale();
974   aViewer->SetScale(aViewer->activeView(), aCurScale);
975   SketcherPrs_Tools::setTextHeight (aCurScale / aPrevScale * SketcherPrs_Tools::getTextHeight());
976   bool isModified = false;
977   QList<AISObjectPtr> aPrsList = aDisplayer->displayedPresentations();
978   foreach (AISObjectPtr aAIS, aPrsList) {
979     Handle(AIS_InteractiveObject) aAisObj = aAIS->impl<Handle(AIS_InteractiveObject)>();
980
981     Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(aAisObj);
982     if (!aDim.IsNull()) {
983       aDim->DimensionAspect()->ArrowAspect()->SetLength(aLen);
984       aContext->Redisplay(aDim, false);
985       isModified = true;
986     }
987   }
988   if (isModified)
989     aDisplayer->updateViewer();
990 }
991
992 bool PartSet_Module::isCustomPrsActivated(const ModuleBase_CustomizeFlag& theFlag) const
993 {
994   return myCustomPrs->isActive(theFlag);
995 }
996
997 void PartSet_Module::activateCustomPrs(const FeaturePtr& theFeature,
998                                        const ModuleBase_CustomizeFlag& theFlag,
999                                        const bool theUpdateViewer)
1000 {
1001   myCustomPrs->activate(theFeature, theFlag, theUpdateViewer);
1002 }
1003
1004 void PartSet_Module::deactivateCustomPrs(const ModuleBase_CustomizeFlag& theFlag,
1005                                          const bool theUpdateViewer)
1006 {
1007   myCustomPrs->deactivate(theFlag, theUpdateViewer);
1008 }
1009
1010 bool PartSet_Module::customisePresentation(ResultPtr theResult, AISObjectPtr thePrs,
1011                                            std::shared_ptr<GeomAPI_ICustomPrs> theCustomPrs)
1012 {
1013   bool aCustomized = false;
1014
1015   XGUI_Workshop* aWorkshop = getWorkshop();
1016   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1017   ObjectPtr anObject = aDisplayer->getObject(thePrs);
1018   if (!anObject)
1019     return aCustomized;
1020
1021   if (!theResult.get()) {
1022     std::vector<int> aColor;
1023     XGUI_CustomPrs::getDefaultColor(anObject, true, aColor);
1024     if (!aColor.empty()) {
1025       aCustomized = thePrs->setColor(aColor[0], aColor[1], aColor[2]);
1026     }
1027   }
1028   // customize dimentional constrains
1029   sketchMgr()->customizePresentation(anObject);
1030
1031   return aCustomized;
1032 }
1033
1034 bool PartSet_Module::afterCustomisePresentation(std::shared_ptr<ModelAPI_Result> theResult,
1035                                                 AISObjectPtr thePrs,
1036                                                 GeomCustomPrsPtr theCustomPrs)
1037 {
1038   bool aCustomized = false;
1039
1040   XGUI_Workshop* aWorkshop = getWorkshop();
1041   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1042   ObjectPtr anObject = aDisplayer->getObject(thePrs);
1043   if (!anObject)
1044     return aCustomized;
1045
1046   std::vector<int> aColor;
1047   bool aUseCustomColor = true;
1048   if (aUseCustomColor)
1049     myOverconstraintListener->getCustomColor(anObject, aColor);
1050   // customize sketch symbol presentation
1051   Handle(AIS_InteractiveObject) anAISIO = thePrs->impl<Handle(AIS_InteractiveObject)>();
1052   if (!anAISIO.IsNull()) {
1053     if (!Handle(SketcherPrs_SymbolPrs)::DownCast(anAISIO).IsNull()) {
1054       Handle(SketcherPrs_SymbolPrs) aPrs = Handle(SketcherPrs_SymbolPrs)::DownCast(anAISIO);
1055       if (!aPrs.IsNull()) {
1056         aPrs->SetCustomColor(aColor);
1057         aCustomized = true;
1058       }
1059     } else if (!Handle(SketcherPrs_Coincident)::DownCast(anAISIO).IsNull()) {
1060       Handle(SketcherPrs_Coincident) aPrs = Handle(SketcherPrs_Coincident)::DownCast(anAISIO);
1061       if (!aPrs.IsNull()) {
1062         aPrs->SetCustomColor(aColor);
1063         aCustomized = true;
1064       }
1065     }
1066   }
1067   // customize sketch dimension constraint presentation
1068   if (!aCustomized) {
1069     if (!aColor.empty()) { // otherwise presentation has the default color
1070       aCustomized = thePrs->setColor(aColor[0], aColor[1], aColor[2]);
1071     }
1072   }
1073   return aCustomized;
1074 }
1075
1076 bool PartSet_Module::customizeObject(ObjectPtr theObject, const ModuleBase_CustomizeFlag& theFlag,
1077                                      const bool theUpdateViewer)
1078 {
1079   bool isRedisplayed = false;
1080   if (myCustomPrs->isActive(theFlag))
1081     isRedisplayed = myCustomPrs->redisplay(theObject, theFlag, theUpdateViewer);
1082
1083   return isRedisplayed;
1084 }
1085
1086 void PartSet_Module::customizeObjectBrowser(QWidget* theObjectBrowser)
1087 {
1088   XGUI_ObjectsBrowser* aOB = dynamic_cast<XGUI_ObjectsBrowser*>(theObjectBrowser);
1089   if (aOB) {
1090     QLabel* aLabel = aOB->activeDocLabel();
1091     aLabel->installEventFilter(myMenuMgr);
1092     connect(aLabel, SIGNAL(customContextMenuRequested(const QPoint&)),
1093           SLOT(onActiveDocPopup(const QPoint&)));
1094     aOB->treeView()->setExpandsOnDoubleClick(false);
1095     connect(aOB->treeView(), SIGNAL(doubleClicked(const QModelIndex&)),
1096       SLOT(onTreeViewDoubleClick(const QModelIndex&)));
1097
1098     Events_Loop* aLoop = Events_Loop::loop();
1099     aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1100   }
1101 }
1102
1103 void PartSet_Module::onActiveDocPopup(const QPoint& thePnt)
1104 {
1105   SessionPtr aMgr = ModelAPI_Session::get();
1106   QAction* aActivatePartAction = myMenuMgr->action("ACTIVATE_PARTSET_CMD");
1107
1108   XGUI_Workshop* aWorkshop = getWorkshop();
1109   QLabel* aHeader = aWorkshop->objectBrowser()->activeDocLabel();
1110
1111   aActivatePartAction->setEnabled((aMgr->activeDocument() != aMgr->moduleDocument()));
1112
1113   QMenu aMenu;
1114   aMenu.addAction(aActivatePartAction);
1115   aMenu.exec(aHeader->mapToGlobal(thePnt));
1116 }
1117
1118 Handle(AIS_InteractiveObject) PartSet_Module::createPresentation(const ResultPtr& theResult)
1119 {
1120   return mySketchMgr->createPresentation(theResult);
1121 }
1122
1123
1124 ObjectPtr PartSet_Module::findPresentedObject(const AISObjectPtr& theAIS) const
1125 {
1126   ObjectPtr anObject;
1127   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1128   if (aOperation) {
1129     /// If last line finished on vertex the lines creation sequence has to be break
1130     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
1131     if (aPanel) {
1132       ModuleBase_ModelWidget* anActiveWidget = aPanel->activeWidget();
1133       // if there is an active widget, find the presented object in it
1134       if (!anActiveWidget)
1135         anActiveWidget = aPanel->preselectionWidget();
1136
1137       ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
1138                                                                              (anActiveWidget);
1139       if (aWidgetValidated)
1140         anObject = aWidgetValidated->findPresentedObject(theAIS);
1141     }
1142   }
1143   return anObject;
1144 }
1145
1146 bool PartSet_Module::canBeShaded(Handle(AIS_InteractiveObject) theAIS) const
1147 {
1148   bool aCanBeShaged = true;
1149
1150   Handle(PartSet_ResultSketchPrs) aPrs = Handle(PartSet_ResultSketchPrs)::DownCast(theAIS);
1151   if (!aPrs.IsNull())
1152     aCanBeShaged = false;
1153
1154   return aCanBeShaged;
1155 }
1156
1157 void PartSet_Module::addObjectBrowserMenu(QMenu* theMenu) const
1158 {
1159   QObjectPtrList aObjects = myWorkshop->selection()->selectedObjects();
1160   int aSelected = aObjects.size();
1161   SessionPtr aMgr = ModelAPI_Session::get();
1162   QAction* aActivatePartAction = myMenuMgr->action("ACTIVATE_PART_CMD");
1163
1164   bool hasResult = false;
1165   bool hasFeature = false;
1166   bool hasParameter = false;
1167   bool hasCompositeOwner = false;
1168   bool hasResultInHistory = false;
1169   ModuleBase_Tools::checkObjects(aObjects, hasResult, hasFeature, hasParameter,
1170                                   hasCompositeOwner, hasResultInHistory);
1171
1172   ModuleBase_Operation* aCurrentOp = myWorkshop->currentOperation();
1173   if (aSelected == 1) {
1174     ObjectPtr aObject = aObjects.first();
1175     if (aObject) {
1176       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1177       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1178       bool isPart = aPart.get() ||
1179         (aFeature.get() && (aFeature->getKind() == PartSetPlugin_Part::ID()));
1180       if (isPart) {
1181         DocumentPtr aPartDoc;
1182         if (!aPart.get()) {
1183           aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFeature->firstResult());
1184         }
1185         if (aPart.get()) // this may be null is Part feature is disabled
1186           aPartDoc = aPart->partDoc();
1187
1188         theMenu->addAction(aActivatePartAction);
1189         aActivatePartAction->setEnabled((aMgr->activeDocument() != aPartDoc));
1190
1191       } else if (aObject->document() == aMgr->activeDocument()) {
1192         if (hasParameter || hasFeature) {
1193           myMenuMgr->action("EDIT_CMD")->setEnabled(true);
1194           theMenu->addAction(myMenuMgr->action("EDIT_CMD"));
1195           if (aCurrentOp && aFeature.get()) {
1196             if (aCurrentOp->id().toStdString() == aFeature->getKind())
1197               myMenuMgr->action("EDIT_CMD")->setEnabled(false);
1198           }
1199         }
1200       }
1201     }
1202   } else {
1203     if (hasFeature) {
1204       myMenuMgr->action("EDIT_CMD")->setEnabled(aCurrentOp == 0);
1205       theMenu->addAction(myMenuMgr->action("EDIT_CMD"));
1206       theMenu->addSeparator();
1207     }
1208   }
1209   bool aNotDeactivate = (aCurrentOp == 0);
1210   if (!aNotDeactivate) {
1211     aActivatePartAction->setEnabled(false);
1212   }
1213 }
1214
1215 #define EXPAND_PARENT(OBJ) \
1216 QModelIndex aObjIndex = aDataModel->objectIndex(OBJ); \
1217 if (aObjIndex.isValid()) { \
1218   QModelIndex aParent = aObjIndex.parent(); \
1219   int aCount = aDataModel->rowCount(aParent); \
1220   if (aCount == 1) \
1221     aTreeView->setExpanded(aParent, true); \
1222 }
1223
1224
1225 void PartSet_Module::processEvent(const std::shared_ptr<Events_Message>& theMessage)
1226 {
1227   if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_DOCUMENT_CHANGED)) {
1228     // Do not change activation of parts if an operation active
1229     static QStringList aAllowActivationList;
1230     if (aAllowActivationList.isEmpty())
1231       aAllowActivationList <<
1232       QString(PartSetPlugin_Part::ID().c_str()) <<
1233       QString(PartSetPlugin_Duplicate::ID().c_str()) <<
1234       QString(PartSetPlugin_Remove::ID().c_str());
1235     if (myWorkshop->currentOperation() &&
1236       (!aAllowActivationList.contains(myWorkshop->currentOperation()->id())))
1237       return;
1238     XGUI_Workshop* aWorkshop = getWorkshop();
1239     XGUI_DataTree* aTreeView = aWorkshop->objectBrowser()->treeView();
1240     QLabel* aLabel = aWorkshop->objectBrowser()->activeDocLabel();
1241     QPalette aPalet = aLabel->palette();
1242
1243     SessionPtr aMgr = ModelAPI_Session::get();
1244     DocumentPtr aActiveDoc = aMgr->activeDocument();
1245     if (myActivePartIndex.isValid())
1246       aTreeView->setExpanded(myActivePartIndex, false);
1247     XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1248     myActivePartIndex = aDataModel->documentRootIndex(aActiveDoc);
1249     if (myActivePartIndex.isValid())
1250       aTreeView->setExpanded(myActivePartIndex, true);
1251
1252     aLabel->setPalette(aPalet);
1253     aWorkshop->updateCommandStatus();
1254
1255     // Update displayed objects in order to update active color
1256     XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1257     QObjectPtrList aObjects = aDisplayer->displayedObjects();
1258     bool aHidden;
1259     foreach(ObjectPtr aObj, aObjects) {
1260       aHidden = !aObj->data() || !aObj->data()->isValid() ||
1261         aObj->isDisabled() || (!aObj->isDisplayed());
1262       if (!aHidden)
1263         aDisplayer->redisplay(aObj, false);
1264     }
1265     aDisplayer->updateViewer();
1266   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
1267     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
1268         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
1269     std::set<ObjectPtr> aObjects = aUpdMsg->objects();
1270
1271     ObjectPtr aConstrObj;
1272     ObjectPtr aResultObj;
1273     std::set<ObjectPtr>::const_iterator aIt;
1274     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
1275     for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
1276       ObjectPtr aObject = (*aIt);
1277       if ((!aResultObj.get()) && (aObject->groupName() == ModelAPI_ResultBody::group())
1278           && (aObject->document() != aRootDoc))
1279         aResultObj = aObject;
1280       if ((!aConstrObj.get()) && (aObject->groupName() == ModelAPI_ResultConstruction::group())
1281           && (aObject->document() != aRootDoc))
1282         aConstrObj = aObject;
1283       if (aResultObj.get() && aConstrObj.get())
1284         break;
1285     }
1286
1287     if (aResultObj.get() || aConstrObj.get()) {
1288       XGUI_Workshop* aWorkshop = getWorkshop();
1289       XGUI_DataTree* aTreeView = aWorkshop->objectBrowser()->treeView();
1290       XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1291
1292       if (aResultObj.get()) {
1293         EXPAND_PARENT(aResultObj)
1294       }
1295       if (aConstrObj.get()) {
1296         EXPAND_PARENT(aConstrObj)
1297       }
1298     }
1299   }
1300 }
1301
1302 void PartSet_Module::onTreeViewDoubleClick(const QModelIndex& theIndex)
1303 {
1304   if (myWorkshop->currentOperation()) // Do not change activation of parts if an operation active
1305     return;
1306   SessionPtr aMgr = ModelAPI_Session::get();
1307   if (!theIndex.isValid()) {
1308     // It seems that this code is obsolete
1309     //aMgr->setActiveDocument(aMgr->moduleDocument());
1310     return;
1311   }
1312   if (theIndex.column() != 0) // Use only first column
1313     return;
1314
1315   XGUI_Workshop* aWorkshop = getWorkshop();
1316   XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1317   // De not use non editable Indexes
1318   if ((aDataModel->flags(theIndex) & Qt::ItemIsSelectable) == 0)
1319     return;
1320   ObjectPtr aObj = aDataModel->object(theIndex);
1321
1322   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1323   if (!aPart.get()) { // Probably this is Feature
1324     FeaturePtr aPartFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
1325     if (aPartFeature.get() && (aPartFeature->getKind() == PartSetPlugin_Part::ID())) {
1326       aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aPartFeature->firstResult());
1327     }
1328   }
1329   if (aPart.get()) { // if this is a part
1330     if (aPart->partDoc() == aMgr->activeDocument()) {
1331       myMenuMgr->activatePartSet();
1332     } else {
1333       myMenuMgr->activatePart(aPart);
1334     }
1335   }
1336 }
1337
1338
1339 void PartSet_Module::onViewCreated(ModuleBase_IViewWindow*)
1340 {
1341   // z layer is created for all started operations in order to visualize operation AIS presentation
1342   // over the object
1343   Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
1344   if (aContext.IsNull())
1345     return;
1346
1347   Handle(V3d_Viewer) aViewer = aContext->CurrentViewer();
1348   if (myVisualLayerId == 0) {
1349     if (myVisualLayerId == 0)
1350       aViewer->AddZLayer(myVisualLayerId);
1351   } else {
1352     TColStd_SequenceOfInteger aZList;
1353     aViewer->GetAllZLayers(aZList);
1354     bool aFound = false;
1355     for (int i = 1; i <= aZList.Length(); i++) {
1356       if (aZList(i) == myVisualLayerId) {
1357         aFound = true;
1358         break;
1359       }
1360     }
1361     if (!aFound)
1362       aViewer->AddZLayer(myVisualLayerId);
1363   }
1364   // if there is an active operation with validated widget,
1365   // the filters of this widget should be activated in the created view
1366   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1367   if (aOperation) {
1368     ModuleBase_ModelWidget* anActiveWidget = activeWidget();
1369     if (anActiveWidget) {
1370       ModuleBase_WidgetSelector* aWSelector =
1371         dynamic_cast<ModuleBase_WidgetSelector*>(anActiveWidget);
1372       if (aWSelector)
1373         aWSelector->activateSelectionAndFilters(true);
1374     }
1375   }
1376 }
1377
1378 //******************************************************
1379 void PartSet_Module::widgetStateChanged(int thePreviousState)
1380 {
1381   mySketchMgr->widgetStateChanged(thePreviousState);
1382 }
1383
1384 bool PartSet_Module::processEnter(const std::string& thePreviousAttributeID)
1385 {
1386   return mySketchReentrantMgr->processEnter(thePreviousAttributeID);
1387 }
1388
1389 //******************************************************
1390 void PartSet_Module::beforeOperationStopped(ModuleBase_Operation* theOperation)
1391 {
1392   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
1393     mySketchMgr->stopSketch(theOperation);
1394   }
1395 }
1396
1397 //******************************************************
1398 GeomShapePtr PartSet_Module::findShape(const AttributePtr& theAttribute)
1399 {
1400   GeomShapePtr aGeomShape;
1401
1402   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
1403   if (anOperation && sketchMgr()->isNestedSketchOperation(anOperation)) {
1404     aGeomShape = PartSet_Tools::findShapeBy2DPoint(theAttribute, myWorkshop);
1405   }
1406   return aGeomShape;
1407 }
1408
1409 //******************************************************
1410 AttributePtr PartSet_Module::findAttribute(const ObjectPtr& theObject,
1411                                            const GeomShapePtr& theGeomShape)
1412 {
1413   AttributePtr anAttribute;
1414   GeomShapePtr aGeomShape = theGeomShape;
1415   if (!aGeomShape.get()) {
1416     // processing shape of result, e.g. sketch circle center is selected, this is a result
1417     // the geom shape is empty, the shape of result should be used
1418     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1419     if (aResult.get()) {
1420       aGeomShape = aResult->shape();
1421     }
1422   }
1423
1424   if (aGeomShape.get()) {
1425     TopoDS_Shape aTDSShape = aGeomShape->impl<TopoDS_Shape>();
1426     return PartSet_Tools::findAttributeBy2dPoint(theObject, aTDSShape,
1427                                                  mySketchMgr->activeSketch());
1428   }
1429   return anAttribute;
1430 }
1431
1432 //******************************************************
1433 std::shared_ptr<Events_Message> PartSet_Module::reentrantMessage()
1434 {
1435   return sketchReentranceMgr()->reentrantMessage();
1436 }
1437
1438 //******************************************************
1439 void PartSet_Module::setReentrantPreSelection(const std::shared_ptr<Events_Message>& theMessage)
1440 {
1441   sketchReentranceMgr()->setReentrantPreSelection(theMessage);
1442 }
1443
1444 //******************************************************
1445 void PartSet_Module::onChoiceChanged(ModuleBase_ModelWidget* theWidget,
1446                                      int theIndex)
1447 {
1448   PartSet_WidgetChoice* aChoiceWidget = dynamic_cast<PartSet_WidgetChoice*>(theWidget);
1449   if (!aChoiceWidget)
1450     return;
1451
1452   QString aChoiceTitle = aChoiceWidget->getPropertyPanelTitle(theIndex);
1453   if (!aChoiceTitle.isEmpty()) {
1454     ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1455     if (!aOperation)
1456       return;
1457     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
1458     if (aPanel)
1459       aPanel->setWindowTitle(aChoiceTitle);
1460   }
1461 }
1462
1463 //******************************************************
1464 XGUI_Workshop* PartSet_Module::getWorkshop() const
1465 {
1466   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
1467   return aConnector->workshop();
1468 }
1469
1470 //******************************************************
1471 void PartSet_Module::setDefaultConstraintShown()
1472 {
1473   myHasConstraintShown[PartSet_Tools::Geometrical] = true;
1474   myHasConstraintShown[PartSet_Tools::Dimensional] = true;
1475   myHasConstraintShown[PartSet_Tools::Expressions] = false;
1476 }