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