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