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