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