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