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