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