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