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