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