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