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