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