Salome HOME
683173100f44c4d60ed3bb2501798604bda6365d
[modules/shaper.git] / src / PartSet / PartSet_Module.cpp
1 // Copyright (C) 2014-2021  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
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_WidgetBSplinePoints.h"
26 #include "PartSet_WidgetPoint2d.h"
27 #include "PartSet_WidgetPoint2DFlyout.h"
28 #include "PartSet_WidgetShapeSelector.h"
29 #include "PartSet_WidgetMultiSelector.h"
30 #include "PartSet_WidgetFeaturePointSelector.h"
31 #include "PartSet_WidgetEditor.h"
32 #include "PartSet_WidgetFileSelector.h"
33 #include "PartSet_WidgetSketchCreator.h"
34 #include "PartSet_SketcherMgr.h"
35 #include "PartSet_SketcherReentrantMgr.h"
36 #include "PartSet_ResultSketchPrs.h"
37 #include "PartSet_MenuMgr.h"
38 #include "PartSet_CustomPrs.h"
39 #include "PartSet_IconFactory.h"
40 #include "PartSet_OverconstraintListener.h"
41 #include "PartSet_TreeNodes.h"
42 #include "PartSet_FieldStepPrs.h"
43 #include "PartSet_BSplineWidget.h"
44
45 #include "PartSet_Filters.h"
46 #include "PartSet_FilterInfinite.h"
47
48 #ifdef _DEBUG
49 #include <QDebug>
50 #endif
51
52 #include <PartSetPlugin_Remove.h>
53 #include <PartSetPlugin_Part.h>
54 #include <PartSetPlugin_Duplicate.h>
55
56 #include <SketchPlugin_ConstraintCoincidence.h>
57
58 #include <ModuleBase_Operation.h>
59 #include <ModuleBase_IViewer.h>
60 #include <ModuleBase_IViewWindow.h>
61 #include <ModuleBase_IPropertyPanel.h>
62 #include <ModuleBase_ISelectionActivate.h>
63 #include <ModuleBase_WidgetChoice.h>
64 #include <ModuleBase_WidgetEditor.h>
65 #include <ModuleBase_WidgetValidated.h>
66 #include <ModuleBase_Tools.h>
67 #include <ModuleBase_OperationFeature.h>
68 #include <ModuleBase_WidgetFactory.h>
69 #include <ModuleBase_OperationDescription.h>
70 #include <ModuleBase_ViewerPrs.h>
71 #include <ModuleBase_ResultPrs.h>
72 #include <ModuleBase_Preferences.h>
73
74 #include <ModelAPI_ResultField.h>
75 #include <ModelAPI_Object.h>
76 #include <ModelAPI_Events.h>
77 #include <ModelAPI_Validator.h>
78 #include <ModelAPI_Data.h>
79 #include <ModelAPI_Session.h>
80 #include <ModelAPI_ResultBody.h>
81 #include <ModelAPI_AttributeString.h>
82 #include <ModelAPI_AttributeSelectionList.h>
83 #include <ModelAPI_Tools.h>
84 #include <ModelAPI_ResultConstruction.h>
85 #include <ModelAPI_AttributeIntArray.h>
86 #include <ModelAPI_AttributeImage.h>
87 #include <ModelAPI_ResultGroup.h>
88 #include <ModelAPI_ResultParameter.h>
89
90 #include <GeomDataAPI_Point2D.h>
91 #include <GeomDataAPI_Point.h>
92 #include <GeomDataAPI_Dir.h>
93
94 #include <XGUI_ActiveControlMgr.h>
95 #include <XGUI_ActiveControlSelector.h>
96 #include <XGUI_ActionsMgr.h>
97 #include <XGUI_ContextMenuMgr.h>
98 #include <XGUI_DataModel.h>
99 #include <XGUI_Displayer.h>
100 #include <XGUI_ErrorMgr.h>
101 #include <XGUI_FacesPanelSelector.h>
102 #include <XGUI_ModuleConnector.h>
103 #include <XGUI_ObjectsBrowser.h>
104 #include <XGUI_OperationMgr.h>
105 #include <XGUI_PropertyPanel.h>
106 #include <XGUI_SelectionMgr.h>
107 #include <XGUI_Tools.h>
108 #include <XGUI_Workshop.h>
109
110 #include <SketchPlugin_ConstraintAngle.h>
111 #include <SketchPlugin_ConstraintLength.h>
112 #include <SketchPlugin_ConstraintDistance.h>
113 #include <SketchPlugin_ConstraintParallel.h>
114 #include <SketchPlugin_ConstraintPerpendicular.h>
115 #include <SketchPlugin_ConstraintRadius.h>
116 #include <SketchPlugin_Feature.h>
117 #include <SketchPlugin_Projection.h>
118 #include <SketchPlugin_Sketch.h>
119
120 #include <SketcherPrs_SymbolPrs.h>
121 #include <SketcherPrs_PositionMgr.h>
122 #include <SketcherPrs_Coincident.h>
123 #include <SketcherPrs_Tools.h>
124
125 #include <Events_Loop.h>
126 #include <Config_PropManager.h>
127 #include <Config_Keywords.h>
128
129 #include <AIS_InteractiveObject.hxx>
130 #include <PrsDim_Dimension.hxx>
131 #include <StdSelect_TypeOfFace.hxx>
132 #include <TopoDS_Vertex.hxx>
133 #include <TopoDS.hxx>
134 #include <TopoDS_Shape.hxx>
135 #include <BRep_Tool.hxx>
136
137 #include <QObject>
138 #include <QMouseEvent>
139 #include <QString>
140 #include <QTimer>
141 #include <QApplication>
142 #include <QMessageBox>
143 #include <QMainWindow>
144 #include <QLineEdit>
145 #include <QString>
146
147 #include <GeomAlgoAPI_FaceBuilder.h>
148 #include <GeomDataAPI_Dir.h>
149
150 #include <SelectMgr_ListIteratorOfListOfFilter.hxx>
151 #include <Graphic3d_Texture2Dmanual.hxx>
152
153 #include <SUIT_ResourceMgr.h>
154
155 #define FEATURE_ITEM_COLOR "0,0,225"
156
157
158 /*!Create and return new instance of XGUI_Module*/
159 extern "C" PARTSET_EXPORT ModuleBase_IModule* createModule(ModuleBase_IWorkshop* theWshop)
160 {
161   return new PartSet_Module(theWshop);
162 }
163
164 //******************************************************
165 PartSet_Module::PartSet_Module(ModuleBase_IWorkshop* theWshop)
166 : ModuleBase_IModule(theWshop),
167   myIsOperationIsLaunched(false),
168   myVisualLayerId(0),
169   myRoot(0)
170 {
171   new PartSet_IconFactory(this);
172
173   mySketchMgr = new PartSet_SketcherMgr(this);
174   mySketchReentrantMgr = new PartSet_SketcherReentrantMgr(theWshop);
175
176   ModuleBase_IViewer* aViewer = theWshop->viewer();
177   connect(aViewer, SIGNAL(keyRelease(ModuleBase_IViewWindow*, QKeyEvent*)),
178           this, SLOT(onKeyRelease(ModuleBase_IViewWindow*, QKeyEvent*)));
179   connect(aViewer, SIGNAL(viewTransformed(int)),
180           SLOT(onViewTransformed(int)));
181   connect(aViewer, SIGNAL(viewCreated(ModuleBase_IViewWindow*)),
182           SLOT(onViewCreated(ModuleBase_IViewWindow*)));
183   myMenuMgr = new PartSet_MenuMgr(this);
184   myCustomPrs = new PartSet_CustomPrs(theWshop);
185
186   myOverconstraintListener = new PartSet_OverconstraintListener(theWshop);
187
188   Events_Loop* aLoop = Events_Loop::loop();
189   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_DOCUMENT_CHANGED));
190   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
191   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_FEATURE_LICENSE_VALID));
192
193   registerSelectionFilter(SF_GlobalFilter, new PartSet_GlobalFilter(myWorkshop));
194   registerSelectionFilter(SF_FilterInfinite, new PartSet_FilterInfinite(myWorkshop));
195   Handle(PartSet_ResultGroupNameFilter) aCRFilter = new PartSet_ResultGroupNameFilter(myWorkshop);
196   std::set<std::string> aCRGroupNames;
197   aCRGroupNames.insert(ModelAPI_ResultConstruction::group());
198   aCRFilter->setGroupNames(aCRGroupNames);
199   registerSelectionFilter(SF_ResultGroupNameFilter, aCRFilter);
200
201   setDefaultConstraintShown();
202
203   Config_PropManager::registerProp("Visualization", "result_body_color", "Result color",
204     Config_Prop::Color, ModelAPI_ResultBody::DEFAULT_COLOR());
205
206   Config_PropManager::registerProp("Visualization", "result_group_color", "Group color",
207     Config_Prop::Color, ModelAPI_ResultGroup::DEFAULT_COLOR());
208
209   Config_PropManager::registerProp("Visualization", "result_construction_color",
210     "Construction color",
211     Config_Prop::Color,
212     ModelAPI_ResultConstruction::DEFAULT_COLOR());
213
214   Config_PropManager::registerProp("Visualization", "result_part_color", "Part color",
215     Config_Prop::Color, ModelAPI_ResultPart::DEFAULT_COLOR());
216
217   Config_PropManager::registerProp("Visualization", "result_field_color", "Field color",
218     Config_Prop::Color, ModelAPI_ResultField::DEFAULT_COLOR());
219
220   Config_PropManager::registerProp("Visualization", "operation_parameter_color",
221                           "Reference shape wireframe color in operation", Config_Prop::Color,
222                           PartSet_CustomPrs::OPERATION_PARAMETER_COLOR());
223   Config_PropManager::registerProp("Visualization", "operation_result_color",
224                           "Result shape wireframe color in operation", Config_Prop::Color,
225                           PartSet_CustomPrs::OPERATION_RESULT_COLOR());
226   Config_PropManager::registerProp("Visualization", "operation_highlight_color",
227                           "Multi selector item color in operation", Config_Prop::Color,
228                           PartSet_CustomPrs::OPERATION_HIGHLIGHT_COLOR());
229   Config_PropManager::registerProp("Visualization", "operation_remove_feature_color",
230                           "Color of removed feature in operation", Config_Prop::Color,
231                           PartSet_CustomPrs::OPERATION_REMOVE_FEATURE_COLOR());
232   Config_PropManager::registerProp("Visualization", "sketch_preview_plane",
233                           "Color of sketch plane", Config_Prop::Color,
234                           PartSet_CustomPrs::OPERATION_SKETCH_PLANE());
235
236   Config_PropManager::registerProp("Visualization", "hidden_face_transparency",
237                                    "Hidden faces transparency",
238                                    Config_Prop::DblSpin,
239                                    "0.8");
240
241   std::ostringstream aStream;
242   aStream << SketcherPrs_Tools::getDefaultArrowSize();
243   Config_PropManager::registerProp("Visualization", "dimension_arrow_size",
244     "Dimension arrow size", Config_Prop::IntSpin, aStream.str());
245
246   Config_PropManager::registerProp("Visualization", "dimension_font", "Dimension font",
247     Config_Prop::String, "Times-bold");
248
249   aStream.str("");
250   aStream.clear();
251   aStream << SketcherPrs_Tools::getDefaultTextHeight();
252   Config_PropManager::registerProp("Visualization", "dimension_value_size",
253     "Dimension value size", Config_Prop::IntSpin, aStream.str());
254
255   Config_PropManager::registerProp("Visualization", "sketch_dimension_color",
256     "Dimension color",
257     Config_Prop::Color, SKETCH_DIMENSION_COLOR);
258
259   Config_PropManager::registerProp("Visualization", "feature_objectbrowser_color",
260     "Feature items in Object Browser",
261     Config_Prop::Color, FEATURE_ITEM_COLOR);
262
263   Config_PropManager::registerProp("Visualization", "zoom_trihedron_arrows",
264     "Keep trihedron arrows view size constant", Config_Prop::Boolean, "false");
265
266   Config_PropManager::registerProp("Visualization", "axis_arrow_size",
267     "Trihedron arrows constant size", Config_Prop::IntSpin, "10");
268
269   Config_PropManager::registerProp("Shortcuts", "add_parameter_shortcut",
270     "Add parameter in parameters manager dialog",
271     Config_Prop::Shortcut, "Ctrl+A");
272
273   Config_PropManager::registerProp("Windows", "use_hide_faces_panel",
274     "Use HideFaces panel in operations", Config_Prop::Boolean, "false");
275 }
276
277 //******************************************************
278 PartSet_Module::~PartSet_Module()
279 {
280   delete myCustomPrs;
281   delete myOverconstraintListener;
282   delete myRoot;
283 }
284
285 //******************************************************
286 void PartSet_Module::createFeatures()
287 {
288   ModuleBase_IModule::createFeatures();
289   myRoot = new PartSet_RootNode();
290   myRoot->setWorkshop(workshop());
291   ModuleBase_IModule::loadProprietaryPlugins();
292 }
293
294
295 //******************************************************
296 void PartSet_Module::storeSelection()
297 {
298   // cash is used only to restore selection, so it should be filled in storeSelection and
299   // after applying immediatelly cleared in restoreSelection
300   myCurrentSelection.clear();
301   sketchMgr()->storeSelection(PartSet_SketcherMgr::ST_SelectType, myCurrentSelection);
302 }
303
304 //******************************************************
305 void PartSet_Module::restoreSelection()
306 {
307   // cash is used only to restore selection, so it should be filled in storeSelection and
308   // after applying immediatelly cleared in restoreSelection
309   sketchMgr()->restoreSelection(myCurrentSelection);
310   myCurrentSelection.clear();
311 }
312
313 //******************************************************
314 void PartSet_Module::registerValidators()
315 {
316   //Registering of validators
317   SessionPtr aMgr = ModelAPI_Session::get();
318   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
319   aFactory->registerValidator("PartSet_DistanceSelection", new PartSet_DistanceSelection);
320   aFactory->registerValidator("PartSet_LengthSelection", new PartSet_LengthSelection);
321   aFactory->registerValidator("PartSet_PerpendicularSelection", new PartSet_PerpendicularSelection);
322   aFactory->registerValidator("PartSet_ParallelSelection", new PartSet_ParallelSelection);
323   aFactory->registerValidator("PartSet_RadiusSelection", new PartSet_RadiusSelection);
324   aFactory->registerValidator("PartSet_RigidSelection", new PartSet_RigidSelection);
325   aFactory->registerValidator("PartSet_CoincidentSelection", new PartSet_CoincidentSelection);
326   aFactory->registerValidator("PartSet_HVDirSelection", new PartSet_HVDirSelection);
327   aFactory->registerValidator("PartSet_TangentSelection", new PartSet_TangentSelection);
328   aFactory->registerValidator("PartSet_FilletSelection", new PartSet_FilletSelection);
329   aFactory->registerValidator("PartSet_AngleSelection", new PartSet_AngleSelection);
330   aFactory->registerValidator("PartSet_EqualSelection", new PartSet_EqualSelection);
331   aFactory->registerValidator("PartSet_CollinearSelection", new PartSet_CollinearSelection);
332   aFactory->registerValidator("PartSet_MiddlePointSelection", new PartSet_MiddlePointSelection);
333   aFactory->registerValidator("PartSet_DifferentObjects", new PartSet_DifferentObjectsValidator);
334   aFactory->registerValidator("PartSet_DifferentPoints", new PartSet_DifferentPointsValidator);
335   aFactory->registerValidator("PartSet_CoincidentAttr", new PartSet_CoincidentAttr);
336   aFactory->registerValidator("PartSet_MultyTranslationSelection",
337     new PartSet_MultyTranslationSelection);
338   aFactory->registerValidator("PartSet_SplitSelection", new PartSet_SplitSelection);
339   aFactory->registerValidator("PartSet_ProjectionSelection", new PartSet_ProjectionSelection);
340   aFactory->registerValidator("PartSet_IntersectionSelection", new PartSet_IntersectionSelection);
341 }
342
343 //******************************************************
344 void PartSet_Module::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget,
345                                             const bool isToConnect)
346 {
347   mySketchMgr->connectToPropertyPanel(theWidget, isToConnect);
348 }
349
350 //******************************************************
351 void PartSet_Module::operationCommitted(ModuleBase_Operation* theOperation)
352 {
353   if (sketchMgr()->isNestedSketchOperation(theOperation)) {
354     mySketchMgr->commitNestedSketch(theOperation);
355   }
356   /// deactivate of overconstraint listener should be performed after Sketch commit (#2176)
357   if (PartSet_SketcherMgr::isSketchOperation(theOperation))
358     overconstraintListener()->setActive(false);
359
360   /// Restart sketcher operations automatically
361   if (!mySketchReentrantMgr->operationCommitted(theOperation)) {
362     getWorkshop()->selector()->clearSelection();
363   }
364 }
365
366 //******************************************************
367 void PartSet_Module::operationAborted(ModuleBase_Operation* theOperation)
368 {
369   /// Restart sketcher operations automatically
370   mySketchReentrantMgr->operationAborted(theOperation);
371   /// deactivate of overconstraint listener should be performed after Sketch abort (#2176)
372   if (PartSet_SketcherMgr::isSketchOperation(theOperation))
373     overconstraintListener()->setActive(false);
374
375   getWorkshop()->selector()->clearSelection();
376 }
377
378 //******************************************************
379 void PartSet_Module::operationStarted(ModuleBase_Operation* theOperation)
380 {
381   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
382                                                                                 (theOperation);
383   if (aFOperation) {
384     XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(workshop());
385     XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
386
387     ModuleBase_ModelWidget* aFilledWidget = 0;
388     bool aPostonedWidgetActivation = false;
389
390     FeaturePtr aFeature = aFOperation->feature();
391     /// Restart sketcher operations automatically
392     /// it is important to call method of sketch reentrant manager before filling of PP
393     /// because it fills some created feature attributes, these new values should be used
394     /// to fill the property panel
395     mySketchReentrantMgr->operationStarted(theOperation);
396
397     aWorkshop->fillPropertyPanel(aFOperation);
398     // filling the operation values by the current selection
399     // if the operation can be committed after the controls filling, the method perform should
400     // be stopped. Otherwise unnecessary presentations can be shown(e.g. operation prs in sketch)
401     bool isOperationCommitted = false;
402     if (!aFOperation->isEditOperation()) {
403       std::string aGreedAttributeId = ModuleBase_Tools::findGreedAttribute(workshop(), aFeature);
404       // if there is a greed attribute, automatic commit by preselection
405       // for this feature is prohibited
406       aFilledWidget = aFOperation->activateByPreselection(aGreedAttributeId);
407       if (currentOperation() != aFOperation)
408         isOperationCommitted = true;
409       else {
410         if (aGreedAttributeId.empty()) {
411           // a signal should be emitted before the next widget activation
412           // because, the activation of the next widget will give a focus to the widget.
413           // As a result the value of the widget is initialized.
414           // And commit may happens until the value is entered.
415           if (aFilledWidget) {
416             if (mySketchReentrantMgr->canBeCommittedByPreselection())
417               isOperationCommitted = mySketchMgr->operationActivatedByPreselection();
418             // activate the next obligatory widget
419             if (!isOperationCommitted)
420               aPropertyPanel->activateNextWidget(aFilledWidget);
421           }
422         }
423         else { // there is a greed widget
424           const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
425           std::string aFirstAttributeId = aWidgets.front()->attributeID();
426           // activate next widget after greeded if it is the first widget in the panel
427           // else the first panel widget is already activated by operation start
428           if (aFirstAttributeId == aGreedAttributeId)
429             aPostonedWidgetActivation = true;
430         }
431       }
432     } if (!isOperationCommitted) {
433       aWorkshop->connectToPropertyPanel(true);
434       updateSketcherOnStart(aFOperation);
435       updatePresentationsOnStart(aFOperation);
436
437       // the objects of the current operation should be deactivated
438       QObjectPtrList anObjects;
439       anObjects.append(aFeature);
440       std::list<ResultPtr> aResults;
441       ModelAPI_Tools::allResults(aFeature, aResults);
442       std::list<ResultPtr>::const_iterator aIt;
443       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
444         anObjects.append(*aIt);
445       }
446       QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
447       for (; anIt != aLast; anIt++)
448         aWorkshop->deactivateActiveObject(*anIt, false);
449       if (anObjects.size() > 0) {
450         XGUI_Displayer* aDisplayer = aWorkshop->displayer();
451         aDisplayer->updateViewer();
452       }
453       /// state of command actions should be updated after displayed objects modification because
454       /// deactivation(for example) of objects may influence on selection in the viewer
455       /// State of command actions may depend on selection in the viewer(e.g. Sketch)
456       workshop()->updateCommandStatus();
457     }
458     if (aPostonedWidgetActivation) {
459       // if the widget is an empty in the chain of activated widgets, the current operation
460       // is restarted. It should be performed after functionality of the operation starting
461       aPropertyPanel->activateNextWidget(aFilledWidget);
462     }
463   }
464 }
465
466 //******************************************************
467 void PartSet_Module::updateSketcherOnStart(ModuleBase_Operation* theOperation)
468 {
469   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
470     mySketchMgr->startSketch(theOperation);
471   }
472   // It is switched off because of
473   // Task #3067: 5.2.2 Drawing in the sketcher: change the mouse cursor arrow
474   else if (sketchMgr()->isNestedSketchOperation(theOperation)) {
475     mySketchMgr->startNestedSketch(theOperation);
476   }
477 }
478
479 //******************************************************
480 void PartSet_Module::updatePresentationsOnStart(ModuleBase_Operation* theOperation)
481 {
482   ModuleBase_OperationFeature* aFOperation =
483     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
484   if (aFOperation) {
485     myCustomPrs->activate(aFOperation->feature(), ModuleBase_IModule::CustomizeArguments, false);
486     myCustomPrs->activate(aFOperation->feature(), ModuleBase_IModule::CustomizeResults, false);
487   }
488 }
489
490 //******************************************************
491 void PartSet_Module::operationResumed(ModuleBase_Operation* theOperation)
492 {
493   ModuleBase_IModule::operationResumed(theOperation);
494
495   ModuleBase_OperationFeature* aFOperation =
496     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
497   if (aFOperation) {
498     myCustomPrs->activate(aFOperation->feature(), ModuleBase_IModule::CustomizeArguments, false);
499     myCustomPrs->activate(aFOperation->feature(), ModuleBase_IModule::CustomizeResults, false);
500   }
501 }
502
503 //******************************************************
504 void PartSet_Module::operationStopped(ModuleBase_Operation* theOperation)
505 {
506   bool isModifiedArgs = myCustomPrs->deactivate(ModuleBase_IModule::CustomizeArguments, false);
507   bool isModifiedResults = myCustomPrs->deactivate(ModuleBase_IModule::CustomizeResults, false);
508   bool isModified = isModifiedArgs || isModifiedResults;
509
510   if (sketchMgr()->isNestedSketchOperation(theOperation)) {
511     mySketchMgr->stopNestedSketch(theOperation);
512   }
513   else if (PartSet_SketcherMgr::isSketchOperation(theOperation))
514     setDefaultConstraintShown();
515
516   //VSV: Viewer is updated on feature update and redisplay
517   if (isModified) {
518     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myWorkshop);
519     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
520     aDisplayer->updateViewer();
521   }
522
523   QMap<PartSet_Tools::ConstraintVisibleState, bool>::const_iterator
524     anIt = myHasConstraintShown.begin(), aLast = myHasConstraintShown.end();
525   for (; anIt != aLast; anIt++) {
526     mySketchMgr->updateBySketchParameters(anIt.key(), anIt.value());
527   }
528 }
529
530 //******************************************************
531 ModuleBase_Operation* PartSet_Module::currentOperation() const
532 {
533   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
534   XGUI_OperationMgr* anOpMgr = aConnector->workshop()->operationMgr();
535   return anOpMgr->currentOperation();
536 }
537
538 //******************************************************
539 bool PartSet_Module::canUndo() const
540 {
541   bool aCanUndo = false;
542   SessionPtr aMgr = ModelAPI_Session::get();
543   if (aMgr->hasModuleDocument() && aMgr->canUndo()) {
544     aCanUndo = !aMgr->isOperation();
545     if (!aCanUndo) // check the enable state additionally by sketch manager
546       aCanUndo = aMgr->canUndo();
547   }
548   return aCanUndo;
549 }
550
551 //******************************************************
552 bool PartSet_Module::canRedo() const
553 {
554   bool aCanRedo = false;
555   SessionPtr aMgr = ModelAPI_Session::get();
556   if (aMgr->hasModuleDocument() && aMgr->canRedo()) {
557     aCanRedo = !aMgr->isOperation();
558     if (!aCanRedo) // check the enable state additionally by sketch manager
559       aCanRedo = aMgr->canRedo();
560   }
561   return aCanRedo;
562 }
563
564 //******************************************************
565 bool PartSet_Module::canApplyAction(const ObjectPtr& theObject, const QString& theActionId) const
566 {
567   bool aValid = true;
568   if (theActionId == "MOVE_CMD" || theActionId == "MOVE_SPLIT_CMD") {
569     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
570     if (aFeature) {
571       ResultPtr aResult = ModuleBase_Tools::firstResult(aFeature);
572       // part features can not be moved in the history.
573       if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group())
574         aValid = false;
575     }
576   }
577   return aValid;
578 }
579
580 //******************************************************
581 bool PartSet_Module::canEraseObject(const ObjectPtr& theObject) const
582 {
583   // the sketch manager put the restriction to the objects erase
584   return mySketchMgr->canEraseObject(theObject);
585 }
586
587 //******************************************************
588 bool PartSet_Module::canDisplayObject(const ObjectPtr& theObject) const
589 {
590   // the sketch manager put the restriction to the objects display
591   return mySketchMgr->canDisplayObject(theObject);
592 }
593
594 //******************************************************
595 bool PartSet_Module::canUsePreselection(const QString& thePreviousOperationKind,
596                                         const QString& theStartedOperationKind)
597 {
598   if (ModuleBase_IModule::canUsePreselection(thePreviousOperationKind, theStartedOperationKind))
599     return true;
600
601   return mySketchMgr->isNestedSketchFeature(theStartedOperationKind);
602 }
603
604 /*void PartSet_Module::processHiddenObject(const std::list<ObjectPtr>& theObjects)
605 {
606   mySketchMgr->processHiddenObject(theObjects);
607 }*/
608
609 //******************************************************
610 bool PartSet_Module::canActivateSelection(const ObjectPtr& theObject) const
611 {
612   bool aCanActivate = ModuleBase_IModule::canActivateSelection(theObject);
613
614   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
615   bool isSketchOp = PartSet_SketcherMgr::isSketchOperation(anOperation),
616        isNestedOp = sketchMgr()->isNestedSketchOperation(anOperation);
617   if (isSketchOp || isNestedOp) {
618     // in active sketch operation it is possible to activate operation object in selection
619     // in the edit operation, e.g. points of the line can be moved when the line is edited
620     ModuleBase_OperationFeature* aFOperation =
621       dynamic_cast<ModuleBase_OperationFeature*>(anOperation);
622     aCanActivate = aCanActivate || (aFOperation && aFOperation->isEditOperation());
623   }
624   return aCanActivate;
625 }
626
627 //******************************************************
628 bool PartSet_Module::addViewerMenu(const QMap<QString, QAction*>& theStdActions,
629                                    QWidget* theParent,
630                                    QMap<int, QAction*>& theMenuActions) const
631 {
632   return myMenuMgr->addViewerMenu(theStdActions, theParent, theMenuActions);
633 }
634
635 //******************************************************
636 void PartSet_Module::updateViewerMenu(const QMap<QString, QAction*>& theStdActions)
637 {
638   myMenuMgr->updateViewerMenu(theStdActions);
639 }
640
641 //******************************************************
642 bool PartSet_Module::isActionEnableStateFixed(const int theActionId) const
643 {
644   bool isEnabledFixed = false;
645   if (theActionId == XGUI_ActionsMgr::AcceptAll &&
646       mySketchReentrantMgr->isInternalEditActive())
647     isEnabledFixed = true;
648   return isEnabledFixed;
649 }
650
651 //******************************************************
652 QString PartSet_Module::getFeatureError(const FeaturePtr& theFeature)
653 {
654   QString anError = ModuleBase_IModule::getFeatureError(theFeature);
655   if (anError.isEmpty())
656     anError = sketchMgr()->getFeatureError(theFeature);
657
658   return anError;
659 }
660
661 //******************************************************
662 void PartSet_Module::grantedOperationIds(ModuleBase_Operation* theOperation,
663                                          QStringList& theIds) const
664 {
665   myMenuMgr->grantedOperationIds(theOperation, theIds);
666
667   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
668     XGUI_Workshop* aWorkshop = getWorkshop();
669     theIds.append(aWorkshop->contextMenuMgr()->action("DELETE_CMD")->text());
670   }
671 }
672
673 //******************************************************
674 void PartSet_Module::activeSelectionModes(QIntList& theModes)
675 {
676   if (mySketchMgr->activeSketch().get())
677     PartSet_SketcherMgr::sketchSelectionModes(mySketchMgr->activeSketch(), theModes);
678   else
679     theModes = XGUI_Tools::workshop(myWorkshop)->viewerSelectionModes();
680 }
681
682 //******************************************************
683 void PartSet_Module::moduleSelectionModes(int theModesType, QIntList& theModes)
684 {
685   customSubShapesSelectionModes(theModes);
686   //theModes.append(XGUI_Tools::workshop(myWorkshop)->viewerSelectionModes());
687   //myWorkshop->module()->activeSelectionModes(theModes);
688 }
689
690 //******************************************************
691 void PartSet_Module::moduleSelectionFilters(const QIntList& theFilterTypes,
692                                             SelectMgr_ListOfFilter& theSelectionFilters)
693 {
694   bool isSketchActive = mySketchMgr->activeSketch().get();
695
696   std::map<ModuleBase_SelectionFilterType, Handle(SelectMgr_Filter)>::const_iterator aFiltersIt =
697     mySelectionFilters.begin();
698   for (; aFiltersIt != mySelectionFilters.end(); aFiltersIt++) {
699     int aFilterType = aFiltersIt->first;
700     // do not add not participating filters in given parameters
701     if (!theFilterTypes.contains(aFilterType))
702       continue;
703
704     // using sketch filters only if sketch operation is active
705     if (!isSketchActive &&
706         mySketchMgr->sketchSelectionFilter((ModuleBase_SelectionFilterType)aFilterType))
707       continue;
708
709     // using filtering of construction results only from faces panel
710     if (aFilterType == SF_ResultGroupNameFilter)
711       continue;
712
713     theSelectionFilters.Append(aFiltersIt->second);
714   }
715 }
716
717 //******************************************************
718 void PartSet_Module::customSubShapesSelectionModes(QIntList& theModes)
719 {
720   if (theModes.contains(TopAbs_FACE))
721     theModes.append(SketcherPrs_Tools::Sel_Sketch_Face);
722   if (theModes.contains(TopAbs_WIRE))
723     theModes.append(SketcherPrs_Tools::Sel_Sketch_Wire);
724
725   if (mySketchMgr->activeSketch().get())
726     PartSet_SketcherMgr::sketchSelectionModes(mySketchMgr->activeSketch(), theModes);
727 }
728
729 //******************************************************
730 void PartSet_Module::getGeomSelection(const std::shared_ptr<ModuleBase_ViewerPrs>& theSelected,
731                                       ObjectPtr& theObject, AttributePtr& theAttribute)
732 {
733   ObjectPtr anObject = theSelected->object();
734   GeomShapePtr aShape = theSelected->shape();
735
736   theAttribute = findAttribute(anObject, aShape);
737   // TODO: try to create result if object is an external object
738   theObject = anObject;
739 }
740
741 //******************************************************
742 bool PartSet_Module::isMouseOverWindow()
743 {
744   return mySketchMgr->isMouseOverWindow();
745 }
746
747 //******************************************************
748 bool PartSet_Module::isSketchNeutralPointActivated() const
749 {
750   bool isNeutralPoint = true;
751   if (sketchReentranceMgr()->isInternalEditActive())
752     isNeutralPoint = false;
753   if (myIsOperationIsLaunched)
754     isNeutralPoint = false;
755
756   return isNeutralPoint;
757 }
758
759 //******************************************************
760 void PartSet_Module::closeDocument()
761 {
762   myActivePartIndex = QModelIndex();
763   SketcherPrs_PositionMgr::get()->clearAll();
764 }
765
766 //******************************************************
767 void PartSet_Module::clearViewer()
768 {
769   myCustomPrs->clearPrs();
770
771   XGUI_Workshop* aWorkshop = getWorkshop();
772   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
773   aDisplayer->deactivateSelectionFilters(false);
774 }
775
776 //******************************************************
777 void PartSet_Module::propertyPanelDefined(ModuleBase_Operation* theOperation)
778 {
779   ModuleBase_OperationFeature* aFOperation =
780     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
781   if (!aFOperation)
782     return;
783
784   ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
785   // we have to manually activate the sketch label in edit mode
786   if (PartSet_SketcherMgr::isSketchOperation(aFOperation) &&  (aFOperation->isEditOperation()))
787     aPanel->activateWidget(aPanel->modelWidgets().first());
788 }
789
790 //******************************************************
791 bool PartSet_Module::createWidgets(const FeaturePtr& theFeature, const QString& theXmlRepr,
792                                    QList<ModuleBase_ModelWidget*>& theWidgets) const
793 {
794   bool aProcessed = false;
795
796   XGUI_Workshop* aWorkshop = getWorkshop();
797   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
798   if (mySketchMgr->activeSketch().get() && aPropertyPanel) {
799     ModuleBase_ISelection* aSelection = workshop()->selection();
800     // click on a point in sketch leads here with the point is highlighted, not yet selected
801     QList<ModuleBase_ViewerPrsPtr> aPreselection = aSelection->getHighlighted();
802     if (aPreselection.size() == 1) {
803       ModuleBase_ViewerPrsPtr aSelectedPrs = aPreselection[0];
804       ObjectPtr anObject = aSelectedPrs->object();
805
806       FeaturePtr aFeature = ModelAPI_Feature::feature(anObject);
807       GeomShapePtr aShape = aSelectedPrs->shape();
808       // click on the digit of dimension constrain comes here
809       // with an empty shape, so we need the check
810       if (aFeature == theFeature && aShape.get() && !aShape->isNull()) {
811         // if feature has only one result and shape of result is equal to selected shape
812         // this attribute is not processed. It is a case of Sketch Point.
813         if (aFeature->results().size() == 1) {
814           ResultPtr aResult = aFeature->results().front();
815           if (aResult.get() && aResult->shape()->isEqual(aShape))
816             return aProcessed;
817         }
818         const TopoDS_Shape& aTDShape = aShape->impl<TopoDS_Shape>();
819         std::pair<AttributePtr, int> anAttribute =
820             PartSet_Tools::findAttributeBy2dPoint(anObject, aTDShape, mySketchMgr->activeSketch());
821         if (anAttribute.first.get()) {
822           ModuleBase_WidgetFactory aFactory(theXmlRepr.toStdString(), workshop());
823
824           const std::string anAttributeId = anAttribute.first->id();
825           aFactory.createWidget(aPropertyPanel->contentWidget(), anAttributeId);
826
827           theWidgets = aFactory.getModelWidgets();
828           // it is possible that the point does not present in XML definition,
829           // in this case, we assume that it is not processed by this module
830           // e.g. "Intersection point" feature
831           aProcessed = !theWidgets.isEmpty();
832         }
833       }
834     }
835   }
836   return aProcessed;
837 }
838
839 //******************************************************
840 void PartSet_Module::onSelectionChanged()
841 {
842   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
843   if (!aOperation)
844     return;
845
846   bool isSketcherOp = false;
847   // An edit operation is enable only if the current opeation is the sketch operation
848   if (mySketchMgr->activeSketch()) {
849     if (PartSet_Tools::sketchPlane(mySketchMgr->activeSketch()))
850       isSketcherOp = PartSet_SketcherMgr::isSketchOperation(aOperation);
851   }
852   if (isSketcherOp) {
853     // Editing of constraints can be done on selection
854     ModuleBase_ISelection* aSelect = myWorkshop->selection();
855     QList<ModuleBase_ViewerPrsPtr> aSelected = aSelect->getSelected();
856     if (aSelected.size() == 1) {
857       ModuleBase_ViewerPrsPtr aPrs = aSelected.first();
858       ObjectPtr aObject = aPrs->object();
859       FeaturePtr aFeature = ModelAPI_Feature::feature(aObject);
860       if (aFeature) {
861         std::string aId = aFeature->getKind();
862         if ((aId == SketchPlugin_ConstraintRadius::ID()) ||
863             (aId == SketchPlugin_ConstraintLength::ID()) ||
864             (aId == SketchPlugin_ConstraintDistance::ID()) ||
865             (aId == SketchPlugin_ConstraintAngle::ID())) {
866           editFeature(aFeature);
867         }
868       }
869     }
870   }
871 }
872
873 //******************************************************
874 void PartSet_Module::onKeyRelease(ModuleBase_IViewWindow* theWnd, QKeyEvent* theEvent)
875 {
876   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
877   XGUI_OperationMgr* anOpMgr = aConnector->workshop()->operationMgr();
878   anOpMgr->onKeyReleased(theWnd->viewPort(), theEvent);
879 }
880
881 //******************************************************
882 ModuleBase_ModelWidget* PartSet_Module::createWidgetByType(const std::string& theType,
883                                                            QWidget* theParent,
884                                                            Config_WidgetAPI* theWidgetApi)
885 {
886   ModuleBase_IWorkshop* aWorkshop = workshop();
887   ModuleBase_ModelWidget* aWgt = NULL;
888   if (theType == "sketch-start-label") {
889     PartSet_WidgetSketchLabel* aLabelWgt = new PartSet_WidgetSketchLabel(theParent, aWorkshop,
890                                                                theWidgetApi, myHasConstraintShown);
891     connect(aLabelWgt, SIGNAL(planeSelected(const std::shared_ptr<GeomAPI_Pln>&)),
892       mySketchMgr, SLOT(onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>&)));
893     connect(aLabelWgt, SIGNAL(showConstraintToggled(int, bool)),
894       mySketchMgr, SLOT(onShowConstraintsToggle(int, bool)));
895     connect(aLabelWgt, SIGNAL(showFreePoints(bool)), mySketchMgr, SLOT(onShowPoints(bool)));
896     connect(aLabelWgt, SIGNAL(autoConstraints(bool)),
897       sketchReentranceMgr(), SLOT(onAutoConstraints(bool)));
898     aLabelWgt->setShowPointsState(mySketchMgr->isShowFreePointsShown());
899     aWgt = aLabelWgt;
900   } else if (theType == "sketch-2dpoint_selector") {
901     PartSet_WidgetPoint2D* aPointWgt = new PartSet_WidgetPoint2D(theParent, aWorkshop,
902                                                                  theWidgetApi);
903     aPointWgt->setSketch(mySketchMgr->activeSketch());
904     connect(aPointWgt, SIGNAL(vertexSelected()), sketchReentranceMgr(), SLOT(onVertexSelected()));
905     aWgt = aPointWgt;
906   }else if (theType == "sketch-2dpoint_flyout_selector") {
907     PartSet_WidgetPoint2DFlyout* aPointWgt = new PartSet_WidgetPoint2DFlyout(theParent, aWorkshop,
908                                                                              theWidgetApi);
909     aPointWgt->setSketch(mySketchMgr->activeSketch());
910     connect(aPointWgt, SIGNAL(vertexSelected()), sketchReentranceMgr(), SLOT(onVertexSelected()));
911     aWgt = aPointWgt;
912   } else if (theType == "sketch_shape_selector") {
913     PartSet_WidgetShapeSelector* aShapeSelectorWgt =
914                           new PartSet_WidgetShapeSelector(theParent, aWorkshop, theWidgetApi);
915     aShapeSelectorWgt->setSketcher(mySketchMgr->activeSketch());
916     aWgt = aShapeSelectorWgt;
917   } else if (theType == "sketch_multi_selector") {
918     PartSet_WidgetMultiSelector* aShapeSelectorWgt =
919                           new PartSet_WidgetMultiSelector(theParent, aWorkshop, theWidgetApi);
920     aShapeSelectorWgt->setSketcher(mySketchMgr->activeSketch());
921     aWgt = aShapeSelectorWgt;
922   }
923   else if (theType == "sketch_feature_point_selector") {
924     PartSet_WidgetFeaturePointSelector* aPointSelectorWgt =
925             new PartSet_WidgetFeaturePointSelector(theParent, aWorkshop, theWidgetApi);
926     aPointSelectorWgt->setSketcher(mySketchMgr->activeSketch());
927     aWgt = aPointSelectorWgt;
928   }
929   else if (theType == "sketch-bspline_selector") {
930     PartSet_WidgetBSplinePoints* aBSplineWgt =
931         new PartSet_WidgetBSplinePoints(theParent, aWorkshop, theWidgetApi);
932     aBSplineWgt->setSketch(mySketchMgr->activeSketch());
933     aWgt = aBSplineWgt;
934   }
935   else if (theType == WDG_DOUBLEVALUE_EDITOR) {
936     aWgt = new PartSet_WidgetEditor(theParent, aWorkshop, theWidgetApi);
937   } else if (theType == "export_file_selector") {
938     aWgt = new PartSet_WidgetFileSelector(theParent, aWorkshop, theWidgetApi);
939   } else if (theType == "sketch_launcher") {
940     aWgt = new PartSet_WidgetSketchCreator(theParent, this, theWidgetApi);
941   }
942   else if (theType == "module_choice") {
943     aWgt = new ModuleBase_WidgetChoice(theParent, theWidgetApi);
944     connect(aWgt, SIGNAL(itemSelected(ModuleBase_ModelWidget*, int)),
945       this, SLOT(onChoiceChanged(ModuleBase_ModelWidget*, int)));
946   } else if (theType == "bspline-panel") {
947     PartSet_BSplineWidget* aPanel = new PartSet_BSplineWidget(theParent, theWidgetApi);
948     //aPanel->setFeature(theFeature);
949     aWgt = aPanel;
950   }
951   return aWgt;
952 }
953
954 //******************************************************
955 ModuleBase_ModelWidget* PartSet_Module::activeWidget() const
956 {
957   ModuleBase_ModelWidget* anActiveWidget = 0;
958
959   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
960   if (!aOperation)
961     return anActiveWidget;
962
963   ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
964   if (!aPanel)
965     return anActiveWidget;
966
967   return aPanel->activeWidget(true);
968 }
969
970 //******************************************************
971 bool PartSet_Module::deleteObjects()
972 {
973   bool isProcessed = false;
974
975   XGUI_Workshop* aWorkshop = getWorkshop();
976   XGUI_OperationMgr* anOpMgr = aWorkshop->operationMgr();
977
978   //SessionPtr aMgr = ModelAPI_Session::get();
979   // 1. check whether the delete should be processed in the module
980   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
981   bool isSketchOp = PartSet_SketcherMgr::isSketchOperation(anOperation),
982        isNestedOp = sketchMgr()->isNestedSketchOperation(anOperation);
983   if (isSketchOp || isNestedOp) {
984     isProcessed = true;
985     // 2. find selected presentations
986     // selected objects should be collected before the current operation abort because
987     // the abort leads to selection lost on constraint objects. It can be corrected after #386 issue
988     ModuleBase_ISelection* aSel = workshop()->selection();
989     QObjectPtrList aSelectedObj = aSel->selectedPresentations();
990     // if there are no selected objects in the viewer, that means that the selection in another
991     // place cased this method. It is necessary to return the false value to understande in above
992     // method that delete is not processed
993     if (aSelectedObj.count() == 0)
994       return false;
995
996     // avoid delete of the objects, which are not belong to the current sketch
997     // in order to do not delete results of other sketches
998     QObjectPtrList aSketchObjects;
999     QObjectPtrList::const_iterator anIt = aSelectedObj.begin(), aLast = aSelectedObj.end();
1000     for ( ; anIt != aLast; anIt++) {
1001       ObjectPtr anObject = *anIt;
1002       if (mySketchMgr->isObjectOfSketch(anObject)) {
1003         // sketch feature should be used in this list because workshop deletes features only
1004         // results are skipped
1005         FeaturePtr aSketchFeature = ModelAPI_Feature::feature(anObject);
1006         aSketchObjects.append(aSketchFeature);
1007       }
1008     }
1009     // if the selection contains only local selected presentations from other sketches,
1010     // the Delete operation should not be done at all
1011     if (aSketchObjects.size() == 0)
1012       return true;
1013
1014     // 3. start operation
1015     QString aDescription = aWorkshop->contextMenuMgr()->action("DELETE_CMD")->text();
1016     ModuleBase_Operation* anOpAction = new ModuleBase_Operation(aDescription, this);
1017
1018     // the active nested sketch operation should be aborted unconditionally
1019     // the Delete action should be additionally granted for the Sketch operation
1020     // in order to do not abort/commit it
1021     bool isCommitted;
1022     if (!anOpMgr->canStartOperation(anOpAction->id(), isCommitted))
1023       return true; // the objects are processed but can not be deleted
1024
1025     anOpMgr->startOperation(anOpAction);
1026
1027     // WORKAROUND, should be done to avoid viewer highlight update after deletetion of objects
1028     // the problem is in AIS Dimensions recompute
1029     // if a line and the dim are removed, line is the first
1030     // it causes the AIS recompute, where the base line is null,
1031     // the result is empty AIS in the viewer
1032     XGUI_Tools::workshop(myWorkshop)->selector()->clearSelection();
1033
1034     // 4. delete features
1035     // sketch feature should be skipped, only sub-features can be removed
1036     // when sketch operation is active
1037     aWorkshop->deleteFeatures(aSketchObjects);
1038     // 5. stop operation
1039     anOpMgr->commitOperation();
1040   }
1041   return isProcessed;
1042 }
1043
1044 //******************************************************
1045 void PartSet_Module::editFeature(FeaturePtr theFeature)
1046 {
1047   storeConstraintsState(theFeature->getKind());
1048   ModuleBase_IModule::editFeature(theFeature);
1049 }
1050
1051 //******************************************************
1052 bool PartSet_Module::canCommitOperation() const
1053 {
1054   return true;
1055 }
1056
1057 //******************************************************
1058 void PartSet_Module::launchOperation(const QString& theCmdId, const bool& isStartAfterCommitOnly)
1059 {
1060   myIsOperationIsLaunched = true;
1061   storeConstraintsState(theCmdId.toStdString());
1062   updateConstraintsState(theCmdId.toStdString());
1063
1064   ModuleBase_IModule::launchOperation(theCmdId, isStartAfterCommitOnly);
1065
1066   myIsOperationIsLaunched = false;
1067 }
1068
1069 //******************************************************
1070 void PartSet_Module::storeConstraintsState(const std::string& theFeatureKind)
1071 {
1072   if (myWorkshop->currentOperation() &&
1073       myWorkshop->currentOperation()->id().toStdString() == SketchPlugin_Sketch::ID()) {
1074     const QMap<PartSet_Tools::ConstraintVisibleState, bool>& aShownStates =
1075                                                   mySketchMgr->showConstraintStates();
1076     myHasConstraintShown = aShownStates;
1077   }
1078 }
1079
1080 //******************************************************
1081 void PartSet_Module::updateConstraintsState(const std::string& theFeatureKind)
1082 {
1083   if (PartSet_SketcherMgr::constraintsIdList().contains(theFeatureKind.c_str()) ||
1084       PartSet_SketcherMgr::replicationsIdList().contains(theFeatureKind.c_str())) {
1085     // Show constraints if a constraint was anOperation
1086     mySketchMgr->updateBySketchParameters(PartSet_Tools::Geometrical, true);
1087     mySketchMgr->updateBySketchParameters(PartSet_Tools::Dimensional, true);
1088     mySketchMgr->updateBySketchParameters(PartSet_Tools::Expressions,
1089                                           myHasConstraintShown[PartSet_Tools::Expressions]);
1090   }
1091 }
1092
1093 //******************************************************
1094 void PartSet_Module::onObjectDisplayed(ObjectPtr theObject, AISObjectPtr theAIS)
1095 {
1096   Handle(AIS_InteractiveObject) anAIS = theAIS->impl<Handle(AIS_InteractiveObject)>();
1097   if (!anAIS.IsNull()) {
1098     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1099     if (aFeature.get()) {
1100       bool aToUseZLayer = false;
1101       if (PartSet_Tools::findRefsToMeFeature(aFeature,SketchPlugin_Projection::ID()))
1102         aToUseZLayer = true;
1103       else {
1104         CompositeFeaturePtr aParent = ModelAPI_Tools::compositeOwner(aFeature);
1105         aToUseZLayer = (aParent.get() && (aParent->getKind() == SketchPlugin_Sketch::ID()));
1106       }
1107       if (aToUseZLayer) {
1108         Handle(AIS_InteractiveContext) aCtx = anAIS->GetContext();
1109         if (aFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID())
1110           aCtx->SetZLayer(anAIS, Graphic3d_ZLayerId_Top);
1111         else
1112           aCtx->SetZLayer(anAIS, myVisualLayerId);
1113       }
1114     }
1115   }
1116 }
1117
1118 //******************************************************
1119 void PartSet_Module::onBeforeObjectErase(ObjectPtr theObject, AISObjectPtr theAIS)
1120 {
1121   // this is obsolete
1122   // it should be recomputed in order to disappear in the viewer if the corresponded object
1123   // is erased
1124   //if (myCustomPrs->isActive())
1125   //  myCustomPrs->redisplay(theObject, false);
1126 }
1127
1128 //******************************************************
1129 void PartSet_Module::onViewTransformed(int theTrsfType)
1130 {
1131   // Set length of arrows constant in pixel size
1132   // if the operation is panning or rotate or panglobal then do nothing
1133   if ((theTrsfType == 1) || (theTrsfType == 3) || (theTrsfType == 4))
1134     return;
1135   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
1136   Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
1137   if (aContext.IsNull())
1138     return;
1139
1140   //Handle(V3d_View) aView = aViewer->activeView();
1141
1142   XGUI_Workshop* aWorkshop = getWorkshop();
1143   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1144   Handle(V3d_Viewer) aV3dViewer = aContext->CurrentViewer();
1145   Handle(V3d_View) aView;
1146   double aScale = 0;
1147   V3d_ListOfView::Iterator aDefinedViews(aV3dViewer->DefinedViews());
1148   for (; aDefinedViews.More(); aDefinedViews.Next()) {
1149     Handle(V3d_View) aV = aDefinedViews.Value();
1150     double aS = aV->Scale();
1151     if (aS > aScale) {
1152       aScale = aS;
1153       aView = aV;
1154     }
1155   }
1156   if (aView.IsNull())
1157     return;
1158
1159   bool isModified = false;
1160   double aLen = aView->Convert(SketcherPrs_Tools::getConfigArrowSize());
1161   ModuleBase_Operation* aCurrentOperation = myWorkshop->currentOperation();
1162   if (aCurrentOperation &&
1163     (PartSet_SketcherMgr::isSketchOperation(aCurrentOperation) ||
1164      sketchMgr()->isNestedSketchOperation(aCurrentOperation) ||
1165      (aCurrentOperation->id() == "Measurement")))
1166   {
1167     SketcherPrs_Tools::setArrowSize(aLen);
1168     const double aCurScale = aViewer->activeView()->Camera()->Scale();
1169     aViewer->SetScale(aViewer->activeView(), aCurScale);
1170 #ifdef OPTIMIZE_PRS
1171     QList<Handle(AIS_InteractiveObject)> aPrsList = aDisplayer->displayedPresentations();
1172     foreach(Handle(AIS_InteractiveObject) aAisObj, aPrsList) {
1173 #else
1174     QList<AISObjectPtr> aPrsList = aDisplayer->displayedPresentations();
1175     foreach(AISObjectPtr aAIS, aPrsList) {
1176       Handle(AIS_InteractiveObject) aAisObj = aAIS->impl<Handle(AIS_InteractiveObject)>();
1177 #endif
1178       Handle(PrsDim_Dimension) aDim = Handle(PrsDim_Dimension)::DownCast(aAisObj);
1179       if (!aDim.IsNull()) {
1180         aDim->DimensionAspect()->ArrowAspect()->SetLength(aLen);
1181         aContext->Redisplay(aDim, false);
1182         isModified = true;
1183       }
1184     }
1185   }
1186
1187   // Manage trihedron arrows
1188   if (Config_PropManager::boolean("Visualization", "zoom_trihedron_arrows")) {
1189     Handle(AIS_Trihedron) aTrihedron = aViewer->trihedron();
1190     if (!aTrihedron.IsNull()) {
1191       double aAxLen =
1192         aView->Convert(Config_PropManager::integer("Visualization", "axis_arrow_size"));
1193       Handle(Prs3d_DatumAspect) aDatumAspect = aTrihedron->Attributes()->DatumAspect();
1194       double aAxisLen = aDatumAspect->AxisLength(Prs3d_DP_XAxis);
1195       aDatumAspect->SetAttribute(Prs3d_DP_ShadingConeLengthPercent, aAxLen / aAxisLen);
1196       aTrihedron->Attributes()->SetDatumAspect(aDatumAspect);
1197       aContext->Redisplay(aTrihedron, false);
1198       isModified = true;
1199     }
1200   }
1201   if (isModified)
1202     aDisplayer->updateViewer();
1203 }
1204
1205 //******************************************************
1206 bool PartSet_Module::isCustomPrsActivated(const ModuleBase_CustomizeFlag& theFlag) const
1207 {
1208   return myCustomPrs->isActive(theFlag);
1209 }
1210
1211 //******************************************************
1212 void PartSet_Module::activateCustomPrs(const FeaturePtr& theFeature,
1213                                        const ModuleBase_CustomizeFlag& theFlag,
1214                                        const bool theUpdateViewer)
1215 {
1216   myCustomPrs->activate(theFeature, theFlag, theUpdateViewer);
1217 }
1218
1219 //******************************************************
1220 void PartSet_Module::deactivateCustomPrs(const ModuleBase_CustomizeFlag& theFlag,
1221                                          const bool theUpdateViewer)
1222 {
1223   myCustomPrs->deactivate(theFlag, theUpdateViewer);
1224 }
1225
1226 //******************************************************
1227 //bool PartSet_Module::customisePresentation(ResultPtr theResult, AISObjectPtr thePrs,
1228 //                                           std::shared_ptr<GeomAPI_ICustomPrs> theCustomPrs)
1229 //{
1230 //  bool aCustomized = false;
1231 //
1232 //  XGUI_Workshop* aWorkshop = getWorkshop();
1233 //  XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1234 //  ObjectPtr anObject = aDisplayer->getObject(thePrs);
1235 //  if (!anObject)
1236 //    return aCustomized;
1237 //
1238 //  if (!theResult.get()) {
1239 //    std::vector<int> aColor;
1240 //    XGUI_CustomPrs::getDefaultColor(anObject, true, aColor);
1241 //    if (!aColor.empty()) {
1242 //      aCustomized = thePrs->setColor(aColor[0], aColor[1], aColor[2]);
1243 //    }
1244 //  }
1245 //  // customize dimentional constrains
1246 //  sketchMgr()->customisePresentation(anObject);
1247 //
1248 //  return aCustomized;
1249 //}
1250 //
1251 ////******************************************************
1252 //bool PartSet_Module::afterCustomisePresentation(std::shared_ptr<ModelAPI_Result> theResult,
1253 //                                                AISObjectPtr thePrs,
1254 //                                                GeomCustomPrsPtr theCustomPrs)
1255 //{
1256 //  bool aCustomized = false;
1257 //
1258 //  XGUI_Workshop* aWorkshop = getWorkshop();
1259 //  XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1260 //  ObjectPtr anObject = aDisplayer->getObject(thePrs);
1261 //  if (!anObject)
1262 //    return aCustomized;
1263 //
1264 //  std::vector<int> aColor;
1265 //  bool aUseCustomColor = true;
1266 //  if (aUseCustomColor)
1267 //    myOverconstraintListener->getCustomColor(anObject, aColor);
1268 //  // customize sketch symbol presentation
1269 //  Handle(AIS_InteractiveObject) anAISIO = thePrs->impl<Handle(AIS_InteractiveObject)>();
1270 //  if (!anAISIO.IsNull()) {
1271 //    if (!Handle(SketcherPrs_SymbolPrs)::DownCast(anAISIO).IsNull()) {
1272 //      Handle(SketcherPrs_SymbolPrs) aPrs = Handle(SketcherPrs_SymbolPrs)::DownCast(anAISIO);
1273 //      if (!aPrs.IsNull()) {
1274 //        aPrs->SetCustomColor(aColor);
1275 //        aCustomized = true;
1276 //      }
1277 //    } else if (!Handle(SketcherPrs_Coincident)::DownCast(anAISIO).IsNull()) {
1278 //      Handle(SketcherPrs_Coincident) aPrs = Handle(SketcherPrs_Coincident)::DownCast(anAISIO);
1279 //      if (!aPrs.IsNull()) {
1280 //        aPrs->SetCustomColor(aColor);
1281 //        aCustomized = true;
1282 //      }
1283 //    }
1284 //  }
1285 //  // customize sketch dimension constraint presentation
1286 //  if (!aCustomized) {
1287 //    if (!aColor.empty()) { // otherwise presentation has the default color
1288 //      aCustomized = thePrs->setColor(aColor[0], aColor[1], aColor[2]);
1289 //    }
1290 //  }
1291 //  return aCustomized;
1292 //}
1293
1294 //******************************************************
1295 bool PartSet_Module::customizeFeature(ObjectPtr theObject, const ModuleBase_CustomizeFlag& theFlag,
1296                                      const bool theUpdateViewer)
1297 {
1298   bool isRedisplayed = false;
1299   if (myCustomPrs->isActive(theFlag))
1300     isRedisplayed = myCustomPrs->redisplay(theObject, theFlag, theUpdateViewer);
1301
1302   return isRedisplayed;
1303 }
1304
1305 //******************************************************
1306 void PartSet_Module::customizeObjectBrowser(QWidget* theObjectBrowser)
1307 {
1308   XGUI_ObjectsBrowser* aOB = dynamic_cast<XGUI_ObjectsBrowser*>(theObjectBrowser);
1309   if (aOB) {
1310     QLabel* aLabel = aOB->activeDocLabel();
1311     aLabel->installEventFilter(myMenuMgr);
1312     connect(aLabel, SIGNAL(customContextMenuRequested(const QPoint&)),
1313           SLOT(onActiveDocPopup(const QPoint&)));
1314     aOB->treeView()->setExpandsOnDoubleClick(false);
1315     connect(aOB->treeView(), SIGNAL(doubleClicked(const QModelIndex&)),
1316       SLOT(onTreeViewDoubleClick(const QModelIndex&)));
1317
1318     Events_Loop* aLoop = Events_Loop::loop();
1319     aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1320   }
1321 }
1322
1323 //******************************************************
1324 void PartSet_Module::onActiveDocPopup(const QPoint& thePnt)
1325 {
1326   SessionPtr aMgr = ModelAPI_Session::get();
1327   QAction* aActivatePartAction = myMenuMgr->action("ACTIVATE_PARTSET_CMD");
1328
1329   XGUI_Workshop* aWorkshop = getWorkshop();
1330   QLabel* aHeader = aWorkshop->objectBrowser()->activeDocLabel();
1331
1332   aActivatePartAction->setEnabled((aMgr->activeDocument() != aMgr->moduleDocument()));
1333
1334   QMenu aMenu;
1335   aMenu.addAction(aActivatePartAction);
1336
1337 #ifndef HAVE_SALOME
1338   if (aMgr->activeDocument() == aMgr->moduleDocument()) {
1339     DocumentPtr aDoc = aMgr->moduleDocument();
1340     int aNbParts = aDoc->size(ModelAPI_ResultPart::group());
1341     bool aHaveToActivate = false;
1342     for (int i = 0; i < aNbParts; i++) {
1343       ObjectPtr aObj = aDoc->object(ModelAPI_ResultPart::group(), i);
1344       ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1345       if (!aPartRes->partDoc().get()) {
1346         aHaveToActivate = true;
1347         break;
1348       }
1349     }
1350     if (aHaveToActivate) {
1351       QAction* aActivateAllPartAction = myMenuMgr->action("ACTIVATE_ALL_PARTS_CMD");
1352       aMenu.addAction(aActivateAllPartAction);
1353     }
1354   }
1355 #endif
1356
1357   aMenu.exec(aHeader->mapToGlobal(thePnt));
1358 }
1359
1360 //******************************************************
1361 AISObjectPtr PartSet_Module::createPresentation(const ObjectPtr& theObject)
1362 {
1363   Handle(AIS_InteractiveObject) anAISPrs = mySketchMgr->createPresentation(theObject);
1364   if (anAISPrs.IsNull()) {
1365     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1366     if (aResult.get()) {
1367       std::shared_ptr<GeomAPI_Shape> aShapePtr = ModelAPI_Tools::shape(aResult);
1368       if (aShapePtr.get() != NULL)
1369         anAISPrs = new ModuleBase_ResultPrs(aResult);
1370     }
1371     else {
1372       FieldStepPtr aStep =
1373         std::dynamic_pointer_cast<ModelAPI_ResultField::ModelAPI_FieldStep>(theObject);
1374       if (aStep.get()) {
1375         anAISPrs = new PartSet_FieldStepPrs(aStep);
1376       }
1377     }
1378   }
1379   AISObjectPtr anAIS;
1380   if (!anAISPrs.IsNull()) {
1381     Handle(AIS_Shape) aShapePrs = Handle(AIS_Shape)::DownCast(anAISPrs);
1382     if (!aShapePrs.IsNull())
1383       ModuleBase_Tools::setPointBallHighlighting((AIS_Shape*)aShapePrs.get());
1384
1385     anAIS = AISObjectPtr(new GeomAPI_AISObject());
1386     anAIS->setImpl(new Handle(AIS_InteractiveObject)(anAISPrs));
1387     customizePresentation(theObject, anAIS);
1388   }
1389   return anAIS;
1390 }
1391
1392 //******************************************************
1393 double getResultDeflection(const ResultPtr& theResult)
1394 {
1395   double aDeflection = ModelAPI_Tools::getDeflection(theResult);
1396   if (aDeflection < 0)
1397     aDeflection = PartSet_Tools::getDefaultDeflection(theResult);
1398   return aDeflection;
1399 }
1400
1401 //******************************************************
1402 double getResultTransparency(const ResultPtr& theResult)
1403 {
1404   double aTransparency = ModelAPI_Tools::getTransparency(theResult);
1405   if (aTransparency < 0)
1406     aTransparency = PartSet_Tools::getDefaultTransparency();
1407   return aTransparency;
1408 }
1409
1410 static AttributeImagePtr findImage(const ObjectPtr& theResult)
1411 {
1412   AttributeImagePtr anImageAttr;
1413
1414   if (theResult.get()) {
1415     ResultBodyPtr aResultBody =
1416       std::dynamic_pointer_cast<ModelAPI_ResultBody>(theResult);
1417     if (aResultBody.get()) {
1418       anImageAttr = aResultBody->data()->image(ModelAPI_ResultBody::IMAGE_ID());
1419       if (!anImageAttr.get() || !anImageAttr->hasTexture()) {
1420         // try to find an image attribute in parents
1421         ObjectPtr aParent = theResult->document()->parent(theResult);
1422         anImageAttr = findImage(aParent);
1423       }
1424     }
1425   }
1426
1427   return anImageAttr;
1428 }
1429
1430 //******************************************************
1431 void PartSet_Module::setTexture(const AISObjectPtr& thePrs,
1432                                 const ResultPtr& theResult)
1433 {
1434   ResultBodyPtr aResultBody =
1435     std::dynamic_pointer_cast<ModelAPI_ResultBody>(theResult);
1436   if (!aResultBody.get())
1437     return;
1438
1439   AttributeImagePtr anImageAttr = findImage(theResult);
1440   if (!anImageAttr.get() || !anImageAttr->hasTexture())
1441     return;
1442
1443   int aWidth, aHeight;
1444   std::string aFormat;
1445   std::list<unsigned char> aByteList;
1446   anImageAttr->texture(aWidth, aHeight, aByteList, aFormat);
1447
1448   Handle(AIS_InteractiveObject) anAIS = thePrs->impl<Handle(AIS_InteractiveObject)>();
1449   if (!anAIS.IsNull()) {
1450     /// set color to white and change material aspect,
1451     /// in order to keep a natural apect of the image.
1452     thePrs->setColor(255, 255, 255);
1453     Quantity_Color myShadingColor(NCollection_Vec3<float>(1.,  1., 1.));
1454     Handle(AIS_Shape) anAISShape = Handle(AIS_Shape)::DownCast(anAIS);
1455     if (!anAISShape.IsNull())
1456     {
1457       auto myDrawer = anAISShape->Attributes();
1458
1459       myDrawer->ShadingAspect()->SetColor(myShadingColor);
1460       myDrawer->ShadingAspect()->Aspect()->SetDistinguishOn();
1461       Graphic3d_MaterialAspect aMatAspect(Graphic3d_NOM_PLASTIC);
1462       aMatAspect.SetTransparency(0.0);
1463       myDrawer->ShadingAspect()->Aspect()->SetFrontMaterial(aMatAspect);
1464       myDrawer->ShadingAspect()->Aspect()->SetBackMaterial(aMatAspect);
1465
1466       //aPixmap = OCCViewer_Utilities::imageToPixmap( px.toImage());
1467       Handle(Image_PixMap) aPixmap = new Image_PixMap();
1468       aPixmap->InitTrash(Image_PixMap::ImgBGRA, aWidth, aHeight);
1469       std::list<unsigned char>::iterator aByteIter = aByteList.begin();
1470       for (int aLine = 0; aLine < aHeight; ++aLine) {
1471         // convert pixels from ARGB to renderer-compatible RGBA
1472         for (int aByte = 0; aByte < aWidth; ++aByte) {
1473           Image_ColorBGRA& aPixmapBytes = aPixmap->ChangeValue<Image_ColorBGRA>(aLine, aByte);
1474
1475           aPixmapBytes.b() = (Standard_Byte) *aByteIter++;
1476           aPixmapBytes.g() = (Standard_Byte) *aByteIter++;
1477           aPixmapBytes.r() = (Standard_Byte) *aByteIter++;
1478           aPixmapBytes.a() = (Standard_Byte) *aByteIter++;
1479         }
1480       }
1481
1482       anAISShape->Attributes()->ShadingAspect()->Aspect()->SetTextureMap
1483           (new Graphic3d_Texture2Dmanual(aPixmap));
1484       anAISShape->Attributes()->ShadingAspect()->Aspect()->SetTextureMapOn();
1485
1486       anAISShape->SetDisplayMode(AIS_Shaded);
1487     }
1488   }
1489 }
1490
1491 //******************************************************
1492 void PartSet_Module::customizePresentation(const ObjectPtr& theObject,
1493                                            const AISObjectPtr& thePrs) const
1494 {
1495   if (mySketchMgr->isObjectOfSketch(theObject)) {
1496     mySketchMgr->customizeSketchPresentation(theObject, thePrs);
1497   }
1498   else {
1499     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1500     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1501     if (aResult.get()) {
1502       std::vector<int> aColor;
1503       bool isSameDoc = (ModelAPI_Session::get()->activeDocument() == aResult->document());
1504       // Get user defined color for the object
1505       ModelAPI_Tools::getColor(aResult, aColor);
1506       if (isSameDoc) {
1507         bool isCustomized = false;
1508         if (aColor.empty() && aFeature.get()) {
1509           GeomCustomPrsPtr aCustPrs = std::dynamic_pointer_cast<GeomAPI_ICustomPrs>(aFeature);
1510           if (aCustPrs.get()) {
1511             isCustomized = aCustPrs->customisePresentation(aResult, thePrs);
1512           }
1513         }
1514         if (!isCustomized) {
1515           if (aColor.empty()) {
1516             PartSet_Tools::getDefaultColor(aResult, false, aColor);
1517           }
1518           thePrs->setColor(aColor[0], aColor[1], aColor[2]);
1519         }
1520       }
1521       else {
1522         if (aColor.empty()) {
1523           PartSet_Tools::getDefaultColor(aResult, false, aColor);
1524         }
1525         QColor aQColor(aColor[0], aColor[1], aColor[2]);
1526         QColor aNewColor =
1527           QColor::fromHsvF(aQColor.hueF(), aQColor.saturationF() / 3., aQColor.valueF());
1528         thePrs->setColor(aNewColor.red(), aNewColor.green(), aNewColor.blue());
1529       }
1530       thePrs->setDeflection(getResultDeflection(aResult));
1531       thePrs->setTransparency(getResultTransparency(aResult));
1532
1533       /// set texture parameters, if any
1534       setTexture(thePrs, aResult);
1535     }
1536     if (aFeature.get() && (aFeature->getKind() == SketchPlugin_Sketch::ID())) {
1537         thePrs->setWidth(2);
1538     }
1539   }
1540 }
1541
1542
1543 //******************************************************
1544 ObjectPtr PartSet_Module::findPresentedObject(const AISObjectPtr& theAIS) const
1545 {
1546   ObjectPtr anObject;
1547   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1548   if (aOperation) {
1549     /// If last line finished on vertex the lines creation sequence has to be break
1550     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
1551     if (aPanel) {
1552       ModuleBase_ModelWidget* anActiveWidget = aPanel->activeWidget();
1553       // if there is an active widget, find the presented object in it
1554       if (!anActiveWidget)
1555         anActiveWidget = aPanel->preselectionWidget();
1556
1557       ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
1558                                                                              (anActiveWidget);
1559       if (aWidgetValidated)
1560         anObject = aWidgetValidated->findPresentedObject(theAIS);
1561     }
1562   }
1563   return anObject;
1564 }
1565
1566 //******************************************************
1567 bool PartSet_Module::canBeShaded(Handle(AIS_InteractiveObject) theAIS) const
1568 {
1569   bool aCanBeShaged = true;
1570
1571   Handle(PartSet_ResultSketchPrs) aPrs = Handle(PartSet_ResultSketchPrs)::DownCast(theAIS);
1572   if (!aPrs.IsNull())
1573     aCanBeShaged = false;
1574
1575   return aCanBeShaged;
1576 }
1577
1578 //******************************************************
1579 void PartSet_Module::addObjectBrowserMenu(QMenu* theMenu) const
1580 {
1581   QObjectPtrList aObjects = myWorkshop->selection()->selectedObjects();
1582   int aSelected = aObjects.size();
1583   SessionPtr aMgr = ModelAPI_Session::get();
1584   QAction* aActivatePartAction = myMenuMgr->action("ACTIVATE_PART_CMD");
1585
1586   bool hasResult = false;
1587   bool hasFeature = false;
1588   bool hasParameter = false;
1589   bool hasCompositeOwner = false;
1590   bool hasResultInHistory = false;
1591   bool hasFolder = false;
1592   ModuleBase_Tools::checkObjects(aObjects, hasResult, hasFeature, hasParameter,
1593                                   hasCompositeOwner, hasResultInHistory, hasFolder);
1594
1595   ModuleBase_Operation* aCurrentOp = myWorkshop->currentOperation();
1596   if (aSelected == 1) {
1597     ObjectPtr aObject = aObjects.first();
1598     if (aObject) {
1599       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1600       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1601       bool isPart = aPart.get() ||
1602         (aFeature.get() && (aFeature->getKind() == PartSetPlugin_Part::ID()));
1603       if (isPart) {
1604         DocumentPtr aPartDoc;
1605         if (!aPart.get()) {
1606           aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFeature->firstResult());
1607         }
1608         if (aPart.get()) // this may be null is Part feature is disabled
1609           aPartDoc = aPart->partDoc();
1610
1611         theMenu->addAction(aActivatePartAction);
1612         aActivatePartAction->setEnabled((aMgr->activeDocument() != aPartDoc));
1613
1614       } else if (aObject->document() == aMgr->activeDocument()) {
1615         if (hasParameter || hasFeature) {
1616
1617           // disable Edit menu for groups under ImportResult feature
1618           bool isEnabled = true;
1619           if (aFeature.get() && aFeature->getKind() == "Group")
1620           {
1621             std::shared_ptr<ModelAPI_CompositeFeature> anOwner =
1622               ModelAPI_Tools::compositeOwner (aFeature);
1623
1624             if (anOwner.get() && anOwner->getKind() == "ImportResult")
1625             {
1626               myMenuMgr->action("EDIT_CMD")->setEnabled(false);
1627               isEnabled = false;
1628             }
1629           }
1630
1631           if (isEnabled)
1632           {
1633             myMenuMgr->action("EDIT_CMD")->setEnabled(true);
1634             theMenu->addAction(myMenuMgr->action("EDIT_CMD"));
1635             if (aCurrentOp && aFeature.get()) {
1636               if (aCurrentOp->id().toStdString() == aFeature->getKind())
1637                 myMenuMgr->action("EDIT_CMD")->setEnabled(false);
1638             }
1639           }
1640         }
1641       }
1642     }
1643   } else {
1644     if (hasFeature) {
1645       myMenuMgr->action("EDIT_CMD")->setEnabled(aCurrentOp == 0);
1646       theMenu->addAction(myMenuMgr->action("EDIT_CMD"));
1647       theMenu->addSeparator();
1648     }
1649   }
1650   bool aNotDeactivate = (aCurrentOp == 0);
1651   if (!aNotDeactivate) {
1652     aActivatePartAction->setEnabled(false);
1653   }
1654 }
1655
1656 //******************************************************
1657 #define EXPAND_PARENT(OBJ) \
1658 QModelIndex aObjIndex = aDataModel->objectIndex(OBJ); \
1659 if (aObjIndex.isValid()) { \
1660   QModelIndex aParent = aObjIndex.parent(); \
1661   int aCount = aDataModel->rowCount(aParent); \
1662   if (aCount == 1) \
1663     aTreeView->setExpanded(aParent, true); \
1664 }
1665
1666 //******************************************************
1667 void PartSet_Module::processEvent(const std::shared_ptr<Events_Message>& theMessage)
1668 {
1669   if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_DOCUMENT_CHANGED)) {
1670     SessionPtr aMgr = ModelAPI_Session::get();
1671     if (!aMgr->hasModuleDocument()) // if document is closed, do not call the document creation
1672       return;
1673     // Do not change activation of parts if an operation active
1674     static QStringList aAllowActivationList;
1675     if (aAllowActivationList.isEmpty())
1676       aAllowActivationList <<
1677       QString(PartSetPlugin_Part::ID().c_str()) <<
1678       QString(PartSetPlugin_Duplicate::ID().c_str()) <<
1679       QString(PartSetPlugin_Remove::ID().c_str());
1680     if (myWorkshop->currentOperation() &&
1681       (!aAllowActivationList.contains(myWorkshop->currentOperation()->id())))
1682       return;
1683     XGUI_Workshop* aWorkshop = getWorkshop();
1684     bool needUpdate = false;
1685     XGUI_DataTree* aTreeView = 0;
1686     if (aWorkshop->objectBrowser()) {
1687       aTreeView = aWorkshop->objectBrowser()->treeView();
1688       QLabel* aLabel = aWorkshop->objectBrowser()->activeDocLabel();
1689       QPalette aPalet = aLabel->palette();
1690
1691       DocumentPtr aActiveDoc = aMgr->activeDocument();
1692
1693       // Clear active part index if there is no Part documents
1694       // It could be not null if document was closed and opened a new
1695       // without closeDocument call
1696       if (aMgr->allOpenedDocuments().size() <= 1)
1697         myActivePartIndex = QModelIndex();
1698
1699       XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1700       QModelIndex aOldActive = myActivePartIndex;
1701       myActivePartIndex = aDataModel->documentRootIndex(aActiveDoc, 0);
1702       if (myActivePartIndex.isValid()) {
1703         needUpdate = aTreeView->isExpanded(myActivePartIndex);
1704         if (!needUpdate)
1705           aTreeView->setExpanded(myActivePartIndex, true);
1706       }
1707       if ((aOldActive != myActivePartIndex) && (aOldActive.isValid()))
1708         aTreeView->setExpanded(aOldActive, false);
1709
1710       aLabel->setPalette(aPalet);
1711     }
1712     aWorkshop->updateCommandStatus();
1713
1714     // Update displayed objects in order to update active color
1715     XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1716     QObjectPtrList aObjects = aDisplayer->displayedObjects();
1717     bool aHidden;
1718     foreach(ObjectPtr aObj, aObjects) {
1719       aHidden = !aObj->data() || !aObj->data()->isValid() ||
1720         aObj->isDisabled() || (!aObj->isDisplayed());
1721       if (!aHidden) {
1722         aDisplayer->redisplay(aObj, false);
1723       }
1724     }
1725     aDisplayer->updateViewer();
1726     // Update tree items if they are expanded
1727     if (needUpdate) {
1728       aTreeView->viewport()->update(aTreeView->viewport()->rect());
1729     }
1730   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
1731     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
1732         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
1733     std::set<ObjectPtr> aObjects = aUpdMsg->objects();
1734
1735     ObjectPtr aConstrObj;
1736     ObjectPtr aResultObj;
1737     std::set<ObjectPtr>::const_iterator aIt;
1738     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
1739     for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
1740       ObjectPtr aObject = (*aIt);
1741       if ((!aResultObj.get()) && (aObject->groupName() == ModelAPI_ResultBody::group())
1742           && (aObject->document() != aRootDoc))
1743         aResultObj = aObject;
1744       if ((!aConstrObj.get()) && (aObject->groupName() == ModelAPI_ResultConstruction::group())
1745           && (aObject->document() != aRootDoc))
1746         aConstrObj = aObject;
1747       if (aResultObj.get() && aConstrObj.get())
1748         break;
1749     }
1750
1751     if (aResultObj.get() || aConstrObj.get()) {
1752       XGUI_Workshop* aWorkshop = getWorkshop();
1753       XGUI_DataTree* aTreeView = aWorkshop->objectBrowser()->treeView();
1754       XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1755
1756       if (aResultObj.get()) {
1757         EXPAND_PARENT(aResultObj)
1758       }
1759       if (aConstrObj.get()) {
1760         EXPAND_PARENT(aConstrObj)
1761       }
1762     }
1763   }
1764   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY)) {
1765     CompositeFeaturePtr aSketch = mySketchMgr->activeSketch();
1766     if (aSketch.get()) {
1767       ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
1768       if (PartSet_SketcherMgr::isSketchOperation(anOperation) &&
1769         mySketchMgr->previewSketchPlane()->isDisplayed())
1770         mySketchMgr->previewSketchPlane()->createSketchPlane(aSketch, myWorkshop);
1771     }
1772   }
1773   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_FEATURE_LICENSE_VALID)) {
1774     std::shared_ptr<ModelAPI_FeaturesLicenseValidMessage> aMsg =
1775       std::dynamic_pointer_cast<ModelAPI_FeaturesLicenseValidMessage>(theMessage);
1776     myFeaturesValidLicense.insert(aMsg->features().begin(), aMsg->features().end());
1777     processProprietaryFeatures();
1778   }
1779 }
1780
1781 //******************************************************
1782 void PartSet_Module::onTreeViewDoubleClick(const QModelIndex& theIndex)
1783 {
1784   if (myWorkshop->currentOperation()) // Do not change activation of parts if an operation active
1785     return;
1786   SessionPtr aMgr = ModelAPI_Session::get();
1787   if (!theIndex.isValid()) {
1788     // It seems that this code is obsolete
1789     //aMgr->setActiveDocument(aMgr->moduleDocument());
1790     return;
1791   }
1792   if (theIndex.column() != 1) // Use only first column
1793     return;
1794
1795   XGUI_Workshop* aWorkshop = getWorkshop();
1796   XGUI_DataModel* aDataModel = aWorkshop->objectBrowser()->dataModel();
1797   // De not use non editable Indexes
1798   if ((aDataModel->flags(theIndex) & Qt::ItemIsSelectable) == 0)
1799     return;
1800   ObjectPtr aObj = aDataModel->object(theIndex);
1801
1802   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1803   if (!aPart.get()) { // Probably this is Feature
1804     FeaturePtr aPartFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
1805     if (aPartFeature.get() && (aPartFeature->getKind() == PartSetPlugin_Part::ID())) {
1806       aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aPartFeature->firstResult());
1807     }
1808     if (aObj.get())
1809     {
1810       if (!aPart.get() && aObj->groupName() == ModelAPI_ResultParameter::group())
1811       {
1812         QObjectPtrList aSelectedObjects = aWorkshop->objectBrowser()->selectedObjects();
1813         FeaturePtr aFeature;
1814         ResultParameterPtr aParam;
1815         foreach(ObjectPtr aSelected, aSelectedObjects) {
1816           aParam = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aSelected);
1817           if (aParam.get())
1818             break;
1819         }
1820         if (aParam.get())
1821           aFeature = ModelAPI_Feature::feature(aParam);
1822
1823         if (aFeature.get())
1824           editFeature(aFeature);
1825       }
1826     }
1827   }
1828   if (aPart.get()) { // if this is a part
1829     if (aPart->partDoc() == aMgr->activeDocument()) {
1830       myMenuMgr->activatePartSet();
1831     } else {
1832       myMenuMgr->activatePart(aPart);
1833     }
1834   }
1835 }
1836
1837 //******************************************************
1838 void PartSet_Module::onViewCreated(ModuleBase_IViewWindow*)
1839 {
1840   // z layer is created for all started operations in order to visualize operation AIS presentation
1841   // over the object
1842   Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
1843   if (aContext.IsNull())
1844     return;
1845
1846   Handle(V3d_Viewer) aViewer = aContext->CurrentViewer();
1847   if (myVisualLayerId == 0) {
1848     if (myVisualLayerId == 0)
1849       aViewer->AddZLayer(myVisualLayerId);
1850   } else {
1851     TColStd_SequenceOfInteger aZList;
1852     aViewer->GetAllZLayers(aZList);
1853     bool aFound = false;
1854     for (int i = 1; i <= aZList.Length(); i++) {
1855       if (aZList(i) == myVisualLayerId) {
1856         aFound = true;
1857         break;
1858       }
1859     }
1860     if (!aFound)
1861       aViewer->AddZLayer(myVisualLayerId);
1862   }
1863   // if there is an active operation with validated widget,
1864   // the filters of this widget should be activated in the created view
1865   myWorkshop->selectionActivate()->updateSelectionFilters();
1866   myWorkshop->selectionActivate()->updateSelectionModes();
1867 }
1868
1869 //******************************************************
1870 void PartSet_Module::widgetStateChanged(int thePreviousState)
1871 {
1872   mySketchMgr->widgetStateChanged(thePreviousState);
1873 }
1874
1875 //******************************************************
1876 bool PartSet_Module::processEnter(const std::string& thePreviousAttributeID)
1877 {
1878   return mySketchReentrantMgr->processEnter(thePreviousAttributeID);
1879 }
1880
1881 //******************************************************
1882 void PartSet_Module::beforeOperationStopped(ModuleBase_Operation* theOperation)
1883 {
1884   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
1885     mySketchMgr->stopSketch(theOperation);
1886   }
1887 }
1888
1889 //******************************************************
1890 GeomShapePtr PartSet_Module::findShape(const AttributePtr& theAttribute)
1891 {
1892   GeomShapePtr aGeomShape;
1893
1894   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
1895   if (anOperation && sketchMgr()->isNestedSketchOperation(anOperation)) {
1896     aGeomShape = PartSet_Tools::findShapeBy2DPoint(theAttribute, myWorkshop);
1897   }
1898   return aGeomShape;
1899 }
1900
1901 //******************************************************
1902 AttributePtr PartSet_Module::findAttribute(const ObjectPtr& theObject,
1903                                            const GeomShapePtr& theGeomShape)
1904 {
1905   AttributePtr anAttribute;
1906   GeomShapePtr aGeomShape = theGeomShape;
1907   if (!aGeomShape.get()) {
1908     // processing shape of result, e.g. sketch circle center is selected, this is a result
1909     // the geom shape is empty, the shape of result should be used
1910     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1911     if (aResult.get()) {
1912       aGeomShape = aResult->shape();
1913     }
1914   }
1915
1916   if (aGeomShape.get()) {
1917     TopoDS_Shape aTDSShape = aGeomShape->impl<TopoDS_Shape>();
1918     std::pair<AttributePtr, int> anAttrAndIndex =
1919         PartSet_Tools::findAttributeBy2dPoint(theObject, aTDSShape, mySketchMgr->activeSketch());
1920     return anAttrAndIndex.first;
1921   }
1922   return anAttribute;
1923 }
1924
1925 //******************************************************
1926 std::shared_ptr<Events_Message> PartSet_Module::reentrantMessage()
1927 {
1928   return sketchReentranceMgr()->reentrantMessage();
1929 }
1930
1931 //******************************************************
1932 void PartSet_Module::setReentrantPreSelection(const std::shared_ptr<Events_Message>& theMessage)
1933 {
1934   sketchReentranceMgr()->setReentrantPreSelection(theMessage);
1935 }
1936
1937 //******************************************************
1938 void PartSet_Module::onChoiceChanged(ModuleBase_ModelWidget* theWidget,
1939                                      int theIndex)
1940 {
1941   ModuleBase_WidgetChoice* aChoiceWidget = dynamic_cast<ModuleBase_WidgetChoice*>(theWidget);
1942   if (!aChoiceWidget)
1943     return;
1944
1945   QString aChoiceTitle = aChoiceWidget->getPropertyPanelTitle(theIndex);
1946   if (!aChoiceTitle.isEmpty()) {
1947     ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
1948     if (!aOperation)
1949       return;
1950     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
1951     if (aPanel)
1952       aPanel->setWindowTitle(aChoiceTitle);
1953   }
1954 }
1955
1956 //******************************************************
1957 XGUI_Workshop* PartSet_Module::getWorkshop() const
1958 {
1959   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
1960   return aConnector->workshop();
1961 }
1962
1963 void PartSet_Module::setDefaultConstraintShown()
1964 {
1965   myHasConstraintShown[PartSet_Tools::Geometrical] = true;
1966   myHasConstraintShown[PartSet_Tools::Dimensional] = true;
1967   myHasConstraintShown[PartSet_Tools::Expressions] = false;
1968 }
1969
1970 //******************************************************
1971 ModuleBase_ITreeNode* PartSet_Module::rootNode() const
1972 {
1973   return myRoot;
1974 }
1975
1976 //******************************************************
1977 void PartSet_Module::disableCustomMode(ModuleBase_CustomizeFlag theMode) {
1978   myCustomPrs->disableCustomMode(theMode);
1979 }
1980
1981 //******************************************************
1982 void PartSet_Module::enableCustomModes() {
1983   myCustomPrs->enableCustomModes();
1984 }
1985
1986 //******************************************************
1987 void PartSet_Module::onRemoveConflictingConstraints()
1988 {
1989   const std::set<ObjectPtr>& aConstraints = myOverconstraintListener->objectsToRemove();
1990   std::set<ObjectPtr>::const_iterator anIt;
1991
1992   XGUI_Workshop* aWorkshop = getWorkshop();
1993   XGUI_OperationMgr* anOpMgr = aWorkshop->operationMgr();
1994
1995   bool isAllowToNotify = ModuleBase_Preferences::resourceMgr()->booleanValue(SKETCH_TAB_NAME,
1996     "notify_change_constraint");
1997
1998   if (isAllowToNotify) {
1999     anIt = aConstraints.begin();
2000     std::string aText("Conflict in constraints: \n");
2001
2002     for (; anIt != aConstraints.end(); anIt++)
2003     {
2004       ObjectPtr anObject = *anIt;
2005       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
2006       TCollection_AsciiString aStr(aFeature->name().c_str());
2007       std::string aName(aStr.ToCString());
2008       aText += aName + "\n";
2009     }
2010
2011     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myWorkshop);
2012     ModuleBase_Tools::warningAboutConflict(aConnector->desktop(),
2013       aText);
2014   }
2015
2016   ModuleBase_Operation* anOp = anOpMgr->currentOperation();
2017   if (sketchMgr()->isNestedSketchOperation(anOp)) {
2018     std::set<FeaturePtr> aFeatures;
2019     for (anIt = aConstraints.cbegin(); anIt != aConstraints.cend(); anIt++)
2020       aFeatures.insert(ModelAPI_Feature::feature(*anIt));
2021
2022     ModelAPI_Tools::removeFeaturesAndReferences(aFeatures);
2023   }
2024   else {
2025     QObjectPtrList anObjectsList;
2026     for (anIt = aConstraints.cbegin(); anIt != aConstraints.cend(); anIt++)
2027       anObjectsList.append(*anIt);
2028
2029     QString aDescription = aWorkshop->contextMenuMgr()->action("DELETE_CMD")->text();
2030     ModuleBase_Operation* anOpAction = new ModuleBase_Operation(aDescription);
2031
2032     anOpMgr->startOperation(anOpAction);
2033     aWorkshop->deleteFeatures(anObjectsList);
2034     anOpMgr->commitOperation();
2035   }
2036   ModuleBase_Tools::flushUpdated(sketchMgr()->activeSketch());
2037 }