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