Salome HOME
ce055596907252ef8db18aba9684dda1582e4be5
[modules/shaper.git] / src / PartSet / PartSet_Module.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 #include "PartSet_Module.h"
4 #include "PartSet_WidgetSketchLabel.h"
5 #include "PartSet_Validators.h"
6 #include "PartSet_Tools.h"
7 #include "PartSet_WidgetPoint2d.h"
8 #include "PartSet_WidgetPoint2dDistance.h"
9 #include "PartSet_WidgetShapeSelector.h"
10 #include "PartSet_WidgetPoint2dAngle.h"
11 #include "PartSet_WidgetMultiSelector.h"
12 #include "PartSet_WidgetEditor.h"
13 #include "PartSet_WidgetFileSelector.h"
14 #include "PartSet_SketcherMgr.h"
15 #include "PartSet_MenuMgr.h"
16
17 #include <PartSetPlugin_Remove.h>
18 #include <PartSetPlugin_Part.h>
19
20 #include <ModuleBase_Operation.h>
21 #include <ModuleBase_IViewer.h>
22 #include <ModuleBase_IViewWindow.h>
23 #include <ModuleBase_IPropertyPanel.h>
24 #include <ModuleBase_WidgetEditor.h>
25 #include <ModuleBase_FilterFactory.h>
26 #include <ModuleBase_Tools.h>
27 #include <GeomValidators_ShapeType.h>
28
29 #include <GeomValidators_Face.h>
30 #include <GeomValidators_ConstructionComposite.h>
31 #include <GeomValidators_ZeroOffset.h>
32
33
34 #include <ModelAPI_Object.h>
35 #include <ModelAPI_Events.h>
36 #include <ModelAPI_Validator.h>
37 #include <ModelAPI_Data.h>
38 #include <ModelAPI_Session.h>
39 #include <ModelAPI_ShapeValidator.h>
40
41 #include <GeomDataAPI_Point2D.h>
42 #include <GeomDataAPI_Point.h>
43 #include <GeomDataAPI_Dir.h>
44
45 #include <XGUI_Displayer.h>
46 #include <XGUI_Workshop.h>
47 #include <XGUI_OperationMgr.h>
48 #include <XGUI_PropertyPanel.h>
49 #include <XGUI_ModuleConnector.h>
50 #include <XGUI_ContextMenuMgr.h>
51 #include <XGUI_Tools.h>
52 #include <XGUI_ObjectsBrowser.h>
53
54 #include <SketchPlugin_Feature.h>
55 #include <SketchPlugin_Sketch.h>
56 #include <SketchPlugin_Line.h>
57 #include <SketchPlugin_Arc.h>
58 #include <SketchPlugin_Circle.h>
59 #include <SketchPlugin_Point.h>
60 #include <SketchPlugin_ConstraintLength.h>
61 #include <SketchPlugin_ConstraintDistance.h>
62 #include <SketchPlugin_ConstraintParallel.h>
63 #include <SketchPlugin_ConstraintPerpendicular.h>
64 #include <SketchPlugin_ConstraintRadius.h>
65
66 #include <SketcherPrs_SymbolPrs.h>
67 #include <SketcherPrs_Tools.h>
68
69 #include <Events_Loop.h>
70 #include <Config_PropManager.h>
71 #include <Config_Keywords.h>
72
73 #include <StdSelect_TypeOfFace.hxx>
74 #include <TopoDS_Vertex.hxx>
75 #include <TopoDS.hxx>
76 #include <TopoDS_Shape.hxx>
77 #include <BRep_Tool.hxx>
78 #include <AIS_Dimension.hxx>
79
80 #include <QObject>
81 #include <QMouseEvent>
82 #include <QString>
83 #include <QTimer>
84 #include <QApplication>
85 #include <QMessageBox>
86 #include <QMainWindow>
87 #include <QLineEdit>
88
89 #include <GeomAlgoAPI_FaceBuilder.h>
90 #include <GeomDataAPI_Dir.h>
91
92 #ifdef _DEBUG
93 #include <QDebug>
94 #endif
95
96
97
98 /*!Create and return new instance of XGUI_Module*/
99 extern "C" PARTSET_EXPORT ModuleBase_IModule* createModule(ModuleBase_IWorkshop* theWshop)
100 {
101   return new PartSet_Module(theWshop);
102 }
103
104 PartSet_Module::PartSet_Module(ModuleBase_IWorkshop* theWshop)
105   : ModuleBase_IModule(theWshop),
106   myRestartingMode(RM_None), myVisualLayerId(0)
107 {
108   mySketchMgr = new PartSet_SketcherMgr(this);
109   myDataModel = new PartSet_DocumentDataModel(this);
110
111   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWshop);
112   XGUI_Workshop* aWorkshop = aConnector->workshop();
113
114   XGUI_OperationMgr* anOpMgr = aWorkshop->operationMgr();
115   connect(anOpMgr, SIGNAL(keyEnterReleased()), this, SLOT(onEnterReleased()));
116   connect(anOpMgr, SIGNAL(operationActivatedByPreselection()),
117           this, SLOT(onOperationActivatedByPreselection()));
118
119   ModuleBase_IViewer* aViewer = theWshop->viewer();
120   connect(aViewer, SIGNAL(keyRelease(ModuleBase_IViewWindow*, QKeyEvent*)),
121           this, SLOT(onKeyRelease(ModuleBase_IViewWindow*, QKeyEvent*)));
122   connect(aViewer, SIGNAL(viewTransformed(int)),
123           SLOT(onViewTransformed(int)));
124
125   myMenuMgr = new PartSet_MenuMgr(this);
126
127   Events_Loop* aLoop = Events_Loop::loop();
128   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_DOCUMENT_CHANGED));
129 }
130
131 PartSet_Module::~PartSet_Module()
132 {
133   if (!myDocumentShapeFilter.IsNull())
134     myDocumentShapeFilter.Nullify();
135 }
136
137 void PartSet_Module::registerValidators()
138 {
139   //Registering of validators
140   SessionPtr aMgr = ModelAPI_Session::get();
141   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
142   aFactory->registerValidator("PartSet_DistanceSelection", new PartSet_DistanceSelection);
143   aFactory->registerValidator("PartSet_LengthSelection", new PartSet_LengthSelection);
144   aFactory->registerValidator("PartSet_PerpendicularSelection", new PartSet_PerpendicularSelection);
145   aFactory->registerValidator("PartSet_ParallelSelection", new PartSet_ParallelSelection);
146   aFactory->registerValidator("PartSet_RadiusSelection", new PartSet_RadiusSelection);
147   aFactory->registerValidator("PartSet_RigidSelection", new PartSet_RigidSelection);
148   aFactory->registerValidator("PartSet_CoincidentSelection", new PartSet_CoincidentSelection);
149   aFactory->registerValidator("PartSet_HVDirSelection", new PartSet_HVDirSelection);
150   aFactory->registerValidator("PartSet_TangentSelection", new PartSet_TangentSelection);
151   aFactory->registerValidator("PartSet_FilletSelection", new PartSet_FilletSelection);
152
153   aFactory->registerValidator("PartSet_DifferentObjects", new PartSet_DifferentObjectsValidator);
154   aFactory->registerValidator("PartSet_DifferentShapes", new ModelAPI_ShapeValidator);
155
156   aFactory->registerValidator("GeomValidators_ShapeType", new GeomValidators_ShapeType);
157   aFactory->registerValidator("GeomValidators_Face", new GeomValidators_Face);
158
159   aFactory->registerValidator("GeomValidators_ConstructionComposite",
160                               new GeomValidators_ConstructionComposite);
161
162   aFactory->registerValidator("GeomValidators_ZeroOffset",
163                               new GeomValidators_ZeroOffset);
164
165   aFactory->registerValidator("PartSet_SketchEntityValidator",
166                               new PartSet_SketchEntityValidator);
167
168   aFactory->registerValidator("PartSet_SameTypeAttr",
169                               new PartSet_SameTypeAttrValidator);
170 }
171
172 void PartSet_Module::registerFilters()
173 {
174   //Registering of selection filters
175   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
176   ModuleBase_FilterFactory* aFactory = aConnector->selectionFilters();
177 }
178
179 void PartSet_Module::registerProperties()
180 {
181   Config_PropManager::registerProp("Sketch planes", "planes_size", "Size", Config_Prop::Double,
182                                    PLANE_SIZE);
183   Config_PropManager::registerProp("Sketch planes", "planes_thickness", "Thickness",
184                                    Config_Prop::Integer, SKETCH_WIDTH);
185 }
186
187 void PartSet_Module::operationCommitted(ModuleBase_Operation* theOperation) 
188 {
189   if (PartSet_SketcherMgr::isNestedSketchOperation(theOperation)) {
190     mySketchMgr->commitNestedSketch(theOperation);
191   }
192
193   if (theOperation->isEditOperation())
194     return;
195   // the selection is cleared after commit the create operation
196   // in order to do not use the same selected objects in the restarted operation
197   // for common behaviour, the selection is cleared even if the operation is not restarted
198   Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
199   if (!aContext.IsNull())
200     aContext->ClearSelected();
201
202   /// Restart sketcher operations automatically
203   FeaturePtr aFeature = theOperation->feature();
204   std::shared_ptr<SketchPlugin_Feature> aSPFeature = 
205             std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
206   if (aSPFeature && (myRestartingMode == RM_LastFeatureUsed ||
207                      myRestartingMode == RM_EmptyFeatureUsed)) {
208     myLastOperationId = theOperation->id();
209     myLastFeature = myRestartingMode == RM_LastFeatureUsed ? theOperation->feature() : FeaturePtr();
210     
211     launchOperation(myLastOperationId);
212   }
213   breakOperationSequence();
214 }
215
216 void PartSet_Module::breakOperationSequence()
217 {
218   myLastOperationId = "";
219   myLastFeature = FeaturePtr();
220   myRestartingMode = RM_None;
221 }
222
223 void PartSet_Module::operationAborted(ModuleBase_Operation* theOperation)
224 {
225   breakOperationSequence();
226 }
227
228 void PartSet_Module::sendOperation(ModuleBase_Operation* theOperation)
229 {
230   // Install the document filter before any other filter
231   if (myDocumentShapeFilter.IsNull())
232     myDocumentShapeFilter = new PartSet_GlobalFilter(myWorkshop);
233   myWorkshop->viewer()->addSelectionFilter(myDocumentShapeFilter);
234
235   ModuleBase_IModule::sendOperation(theOperation);
236 }
237
238 void PartSet_Module::operationStarted(ModuleBase_Operation* theOperation)
239 {
240   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
241     Handle(V3d_Viewer) aViewer = myWorkshop->viewer()->AISContext()->CurrentViewer();
242     aViewer->AddZLayer(myVisualLayerId);
243     mySketchMgr->startSketch(theOperation);
244   }
245   else if (PartSet_SketcherMgr::isNestedSketchOperation(theOperation)) {
246     mySketchMgr->startNestedSketch(theOperation);
247   }
248 }
249
250 void PartSet_Module::operationStopped(ModuleBase_Operation* theOperation)
251 {
252   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
253     mySketchMgr->stopSketch(theOperation);
254     Handle(V3d_Viewer) aViewer = myWorkshop->viewer()->AISContext()->CurrentViewer();
255     aViewer->RemoveZLayer(myVisualLayerId);
256     myVisualLayerId = 0;
257   }
258   else if (PartSet_SketcherMgr::isNestedSketchOperation(theOperation)) {
259     mySketchMgr->stopNestedSketch(theOperation);
260   }
261   myWorkshop->viewer()->removeSelectionFilter(myDocumentShapeFilter);
262 }
263
264 ModuleBase_Operation* PartSet_Module::currentOperation() const
265 {
266   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
267   XGUI_OperationMgr* anOpMgr = aConnector->workshop()->operationMgr();
268   return anOpMgr->currentOperation();
269 }
270
271 bool PartSet_Module::canUndo() const
272 {
273   bool aCanUndo = false;
274   SessionPtr aMgr = ModelAPI_Session::get();
275   if (aMgr->hasModuleDocument() && aMgr->canUndo()) {
276     aCanUndo = !aMgr->isOperation();
277     if (!aCanUndo) // check the enable state additionally by sketch manager
278       aCanUndo = aMgr->canUndo();
279   }
280   return aCanUndo;
281 }
282
283 bool PartSet_Module::canRedo() const
284 {
285   bool aCanRedo = false;
286   SessionPtr aMgr = ModelAPI_Session::get();
287   if (aMgr->hasModuleDocument() && aMgr->canRedo()) {
288     aCanRedo = !aMgr->isOperation();
289     if (!aCanRedo) // check the enable state additionally by sketch manager
290       aCanRedo = aMgr->canRedo();
291   }
292   return aCanRedo;
293 }
294
295 bool PartSet_Module::canDisplayObject(const ObjectPtr& theObject) const
296 {
297   // the sketch manager put the restriction to the objects display
298   return mySketchMgr->canDisplayObject(theObject);
299 }
300
301 bool PartSet_Module::canActivateSelection(const ObjectPtr& theObject) const
302 {
303   bool aCanActivate = ModuleBase_IModule::canActivateSelection(theObject);
304
305   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
306   bool isSketchOp = PartSet_SketcherMgr::isSketchOperation(anOperation),
307        isNestedOp = PartSet_SketcherMgr::isNestedSketchOperation(anOperation);
308   if (isSketchOp || isNestedOp) {
309     // in active sketch operation it is possible to activate operation object in selection
310     // in the edit operation, e.g. points of the line can be moved when the line is edited
311     aCanActivate = aCanActivate || anOperation->isEditOperation();
312   }
313   return aCanActivate;
314 }
315
316 bool PartSet_Module::addViewerMenu(QMenu* theMenu, const QMap<QString, QAction*>& theStdActions) const
317 {
318   return myMenuMgr->addViewerMenu(theMenu, theStdActions);
319 }
320
321 void PartSet_Module::activeSelectionModes(QIntList& theModes)
322 {
323   theModes.clear();
324   if (mySketchMgr->activeSketch().get())
325     PartSet_SketcherMgr::sketchSelectionModes(theModes);
326 }
327
328 bool PartSet_Module::isMouseOverWindow()
329 {
330   return mySketchMgr->isMouseOverWindow();
331 }
332
333 void PartSet_Module::propertyPanelDefined(ModuleBase_Operation* theOperation)
334 {
335   ModuleBase_IPropertyPanel* aPanel = theOperation->propertyPanel();
336   if (PartSet_SketcherMgr::isSketchOperation(theOperation) &&  (theOperation->isEditOperation())) {
337     // we have to manually activate the sketch label in edit mode
338       aPanel->activateWidget(aPanel->modelWidgets().first());
339       return;
340   }
341
342   // Restart last operation type 
343   if ((theOperation->id() == myLastOperationId) && myLastFeature) {
344     ModuleBase_ModelWidget* aWgt = aPanel->activeWidget();
345     if (theOperation->id().toStdString() == SketchPlugin_Line::ID()) {
346       // Initialise new line with first point equal to end of previous
347       PartSet_WidgetPoint2D* aPnt2dWgt = dynamic_cast<PartSet_WidgetPoint2D*>(aWgt);
348       if (aPnt2dWgt) {
349         std::shared_ptr<ModelAPI_Data> aData = myLastFeature->data();
350         std::shared_ptr<GeomDataAPI_Point2D> aPoint = 
351           std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aData->attribute(SketchPlugin_Line::END_ID()));
352         if (aPoint) {
353           aPnt2dWgt->setPoint(aPoint->x(), aPoint->y());
354           PartSet_Tools::setConstraints(mySketchMgr->activeSketch(), theOperation->feature(), 
355             aWgt->attributeID(), aPoint->x(), aPoint->y());
356           aPanel->activateNextWidget(aPnt2dWgt);
357         }
358       }
359     }
360   } else {
361     // Start editing constraint
362     if (theOperation->isEditOperation()) {
363       // TODO: #391 - to be removed
364       std::string aId = theOperation->id().toStdString();
365       if (PartSet_SketcherMgr::isNestedSketchOperation(theOperation) &&
366           PartSet_SketcherMgr::isDistanceOperation(theOperation)) {
367         // Find and activate widget for management of point for dimension line position
368         QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
369         foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
370           PartSet_WidgetPoint2D* aPntWgt = dynamic_cast<PartSet_WidgetPoint2D*>(aWgt);
371           if (aPntWgt) {
372             aPanel->activateWidget(aPntWgt);
373             return;
374           }
375         }
376       }
377     }
378   }
379 }
380
381
382 void PartSet_Module::onSelectionChanged()
383 {
384   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
385   if (!aOperation)
386     return;
387
388   bool isSketcherOp = false;
389   // An edit operation is enable only if the current opeation is the sketch operation
390   if (mySketchMgr->activeSketch()) {
391     if (PartSet_Tools::sketchPlane(mySketchMgr->activeSketch()))
392       isSketcherOp = PartSet_SketcherMgr::isSketchOperation(aOperation);
393   }
394   if (isSketcherOp) {
395     // Editing of constraints can be done on selection
396     ModuleBase_ISelection* aSelect = myWorkshop->selection();
397     QList<ModuleBase_ViewerPrs> aSelected = aSelect->getSelected();
398     if (aSelected.size() == 1) {
399       ModuleBase_ViewerPrs aPrs = aSelected.first();
400       ObjectPtr aObject = aPrs.object();
401       FeaturePtr aFeature = ModelAPI_Feature::feature(aObject);
402       if (aFeature) {
403         std::string aId = aFeature->getKind();
404         if ((aId == SketchPlugin_ConstraintRadius::ID()) ||
405             (aId == SketchPlugin_ConstraintLength::ID()) || 
406             (aId == SketchPlugin_ConstraintDistance::ID())) {
407           editFeature(aFeature);
408         }
409       }
410     }
411   } 
412 }
413
414 void PartSet_Module::onKeyRelease(ModuleBase_IViewWindow* theWnd, QKeyEvent* theEvent)
415 {
416   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
417   XGUI_OperationMgr* anOpMgr = aConnector->workshop()->operationMgr();
418   anOpMgr->onKeyReleased(theEvent);
419 }
420
421 void PartSet_Module::onEnterReleased()
422 {
423   myRestartingMode = RM_EmptyFeatureUsed;
424 }
425
426 void PartSet_Module::onOperationActivatedByPreselection()
427 {
428   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
429   if(anOperation && PartSet_SketcherMgr::isNestedSketchOperation(anOperation)) {
430     // Set final definitions if they are necessary
431     //propertyPanelDefined(aOperation);
432
433     /// Commit sketcher operations automatically
434     anOperation->commit();
435   }
436 }
437
438 void PartSet_Module::onNoMoreWidgets()
439 {
440   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
441   if (anOperation) {
442     if (PartSet_SketcherMgr::isNestedSketchOperation(anOperation)) {
443       if (myRestartingMode != RM_Forbided)
444         myRestartingMode = RM_LastFeatureUsed;
445       anOperation->commit();
446     }
447   }
448 }
449
450 void PartSet_Module::onVertexSelected()
451 {
452   ModuleBase_Operation* aOperation = myWorkshop->currentOperation();
453   if (aOperation->id().toStdString() == SketchPlugin_Line::ID()) {
454     /// If last line finished on vertex the lines creation sequence has to be break
455     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
456     ModuleBase_ModelWidget* anActiveWidget = aPanel->activeWidget();
457     const QList<ModuleBase_ModelWidget*>& aWidgets = aPanel->modelWidgets();
458     QList<ModuleBase_ModelWidget*>::const_iterator anIt = aWidgets.begin(), aLast = aWidgets.end();
459     bool aFoundWidget = false;
460     bool aFoundObligatory = false;
461     for (; anIt != aLast && !aFoundObligatory; anIt++) {
462       if (!aFoundWidget)
463         aFoundWidget = *anIt == anActiveWidget;
464       else
465         aFoundObligatory = (*anIt)->isObligatory();
466     }
467     if (!aFoundObligatory)
468       myRestartingMode = RM_Forbided;
469   }
470 }
471
472 ModuleBase_ModelWidget* PartSet_Module::createWidgetByType(const std::string& theType, QWidget* theParent,
473                                             Config_WidgetAPI* theWidgetApi, std::string theParentId)
474 {
475   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
476   XGUI_Workshop* aWorkshop = aConnector->workshop();
477   ModuleBase_ModelWidget* aWgt = NULL;
478   if (theType == "sketch-start-label") {
479     PartSet_WidgetSketchLabel* aLabelWgt = new PartSet_WidgetSketchLabel(theParent, 
480       theWidgetApi, theParentId, mySketchMgr->isConstraintsShown());
481     aLabelWgt->setWorkshop(aWorkshop);
482     connect(aLabelWgt, SIGNAL(planeSelected(const std::shared_ptr<GeomAPI_Pln>&)),
483       mySketchMgr, SLOT(onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>&)));
484     connect(aLabelWgt, SIGNAL(showConstraintToggled(bool)),
485       mySketchMgr, SLOT(onShowConstraintsToggle(bool)));
486     aWgt = aLabelWgt;
487   } else if (theType == "sketch-2dpoint_selector") {
488     PartSet_WidgetPoint2D* aPointWgt = new PartSet_WidgetPoint2D(theParent, theWidgetApi, theParentId);
489     aPointWgt->setWorkshop(aWorkshop);
490     aPointWgt->setSketch(mySketchMgr->activeSketch());
491     connect(aPointWgt, SIGNAL(vertexSelected()), this, SLOT(onVertexSelected()));
492     aWgt = aPointWgt;
493   } else if (theType == "point2ddistance") {
494     PartSet_WidgetPoint2dDistance* aDistanceWgt = new PartSet_WidgetPoint2dDistance(theParent, theWidgetApi, theParentId);
495     aDistanceWgt->setWorkshop(aWorkshop);
496     aDistanceWgt->setSketch(mySketchMgr->activeSketch());
497     aWgt = aDistanceWgt;
498   } else if(theType == "point2dangle") {
499     PartSet_WidgetPoint2dAngle* anAngleWgt = new PartSet_WidgetPoint2dAngle(theParent, theWidgetApi, theParentId);
500     anAngleWgt->setWorkshop(aWorkshop);
501     anAngleWgt->setSketch(mySketchMgr->activeSketch());
502     aWgt = anAngleWgt;
503   } else if (theType == "sketch_shape_selector") {
504     PartSet_WidgetShapeSelector* aShapeSelectorWgt =
505       new PartSet_WidgetShapeSelector(theParent, workshop(), theWidgetApi, theParentId);
506     aShapeSelectorWgt->setSketcher(mySketchMgr->activeSketch());
507     aWgt = aShapeSelectorWgt;
508   } else if (theType == "sketch_multi_selector") {
509     PartSet_WidgetMultiSelector* aShapeSelectorWgt =
510       new PartSet_WidgetMultiSelector(theParent, workshop(), theWidgetApi, theParentId);
511     aShapeSelectorWgt->setSketcher(mySketchMgr->activeSketch());
512     aWgt = aShapeSelectorWgt;
513   } else if (theType == WDG_DOUBLEVALUE_EDITOR) {
514     aWgt = new PartSet_WidgetEditor(theParent, workshop(), theWidgetApi, theParentId);
515   } else if (theType == "export_file_selector") {
516     aWgt = new PartSet_WidgetFileSelector(theParent, workshop(), theWidgetApi, theParentId);
517   } 
518   return aWgt;
519 }
520
521
522 bool PartSet_Module::deleteObjects()
523 {
524   SessionPtr aMgr = ModelAPI_Session::get();
525   // 1. check whether the delete should be processed in the module
526   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
527   bool isSketchOp = PartSet_SketcherMgr::isSketchOperation(anOperation),
528        isNestedOp = PartSet_SketcherMgr::isNestedSketchOperation(anOperation);
529   if (isSketchOp || isNestedOp) {
530     // 2. find selected presentations
531     // selected objects should be collected before the current operation abort because
532     // the abort leads to selection lost on constraint objects. It can be corrected after #386 issue
533     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(workshop());
534     XGUI_Workshop* aWorkshop = aConnector->workshop();
535     ModuleBase_ISelection* aSel = workshop()->selection();
536     QObjectPtrList aSelectedObj = aSel->selectedPresentations();
537     // if there are no selected objects in the viewer, that means that the selection in another
538     // place cased this method. It is necessary to return the false value to understande in above
539     // method that delete is not processed
540     if (aSelectedObj.count() == 0)
541       return false;
542
543     // avoid delete of the objects, which are not belong to the current sketch
544     // in order to do not delete results of other sketches
545     QObjectPtrList aSketchObjects;
546     QObjectPtrList::const_iterator anIt = aSelectedObj.begin(), aLast = aSelectedObj.end();
547     for ( ; anIt != aLast; anIt++) {
548       ObjectPtr anObject = *anIt;
549       if (mySketchMgr->isObjectOfSketch(anObject)) {
550         // sketch feature should be used in this list because workshop deletes features only
551         // results are skipped
552         FeaturePtr aSketchFeature = ModelAPI_Feature::feature(anObject);
553         aSketchObjects.append(aSketchFeature);
554       }
555     }
556     // if the selection contains only local selected presentations from other sketches,
557     // the Delete operation should not be done at all
558     if (aSketchObjects.size() == 0)
559       return true;
560
561     // the active nested sketch operation should be aborted unconditionally
562     if (isNestedOp)
563       anOperation->abort();
564
565     // 3. start operation
566     QString aDescription = aWorkshop->contextMenuMgr()->action("DELETE_CMD")->text();
567     aMgr->startOperation(aDescription.toStdString());
568
569     // 4. delete features
570     // sketch feature should be skipped, only sub-features can be removed
571     // when sketch operation is active
572     std::set<FeaturePtr> anIgnoredFeatures;
573     anIgnoredFeatures.insert(mySketchMgr->activeSketch());
574     aWorkshop->deleteFeatures(aSketchObjects, anIgnoredFeatures);
575   
576     // 5. stop operation
577     aWorkshop->displayer()->updateViewer();
578     aMgr->finishOperation();
579   } else {
580     bool isPartRemoved = false;
581     // Delete part with help of PartSet plugin
582     // TODO: the deleted objects has to be processed by multiselection
583     QObjectPtrList aObjects = myWorkshop->selection()->selectedObjects();
584     if (aObjects.size() == 1) {
585       ObjectPtr aObj = aObjects.first();
586       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
587       if (aFeature.get() && (aFeature->getKind() == PartSetPlugin_Part::ID())) {
588         // Remove feature should be created in the document of the part results
589         ResultPtr aPartResult = aFeature->firstResult();
590         if (aPartResult.get()) {
591           std::shared_ptr<ModelAPI_ResultPart> aPart =
592                        std::dynamic_pointer_cast<ModelAPI_ResultPart>(aPartResult);
593           DocumentPtr aPartDoc = aPart->partDoc();
594           if (aPartDoc.get()) {
595             aMgr->startOperation(PartSetPlugin_Remove::ID());
596             FeaturePtr aFeature = aPartDoc->addFeature(PartSetPlugin_Remove::ID());
597             aFeature->execute();
598             aMgr->finishOperation();
599             isPartRemoved = true;
600           }
601         }
602       }
603     }
604     return isPartRemoved;
605   }
606   return true;
607 }
608
609 void PartSet_Module::onFeatureTriggered()
610 {
611   SessionPtr aMgr = ModelAPI_Session::get();
612   // 1. check whether the delete should be processed in the module
613   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
614   bool isNestedOp = PartSet_SketcherMgr::isNestedCreateOperation(anOperation);
615   if (isNestedOp) {
616     // in case if in the viewer nothing is displayed, the create operation should not be
617     // comitted even if all values of the feature are initialized
618     if (!mySketchMgr->canDisplayCurrentCreatedFeature()) {
619       QAction* aCmd = dynamic_cast<QAction*>(sender());
620       //Do nothing on uncheck
621       if (aCmd->isCheckable() && !aCmd->isChecked())
622         return;
623
624       // the action information should be saved before the operation is aborted
625       // because this abort leads to update command status, which unchecks this action
626       anOperation->abort();
627
628       launchOperation(aCmd->data().toString());
629     }
630   }
631   ModuleBase_IModule::onFeatureTriggered();
632 }
633
634 void PartSet_Module::onObjectDisplayed(ObjectPtr theObject, AISObjectPtr theAIS) 
635 {
636   Handle(AIS_InteractiveObject) anAIS = theAIS->impl<Handle(AIS_InteractiveObject)>();
637   if (!anAIS.IsNull()) {
638     Handle(AIS_InteractiveContext) aCtx = anAIS->GetContext();
639     Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(anAIS);
640     if (!aDim.IsNull()) {
641       aCtx->SetZLayer(aDim, myVisualLayerId);
642     } else {
643       Handle(SketcherPrs_SymbolPrs) aCons = Handle(SketcherPrs_SymbolPrs)::DownCast(anAIS);
644       if (!aCons.IsNull())
645         aCtx->SetZLayer(aCons, myVisualLayerId);
646     }
647   }
648 }
649
650 void PartSet_Module::onViewTransformed(int theTrsfType)
651 {
652   // Set length of arrows constant in pixel size
653   // if the operation is panning or rotate or panglobal then do nothing
654   if ((theTrsfType == 1) || (theTrsfType == 3) || (theTrsfType == 4))
655     return;
656
657   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
658   //Handle(V3d_View) aView = aViewer->activeView();
659
660   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myWorkshop);
661   XGUI_Workshop* aWorkshop = aConnector->workshop();
662   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
663   Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
664
665   Handle(V3d_Viewer) aV3dViewer = aContext->CurrentViewer();
666   Handle(V3d_View) aView;
667   double aScale = 0;
668   for (aV3dViewer->InitDefinedViews(); 
669        aV3dViewer->MoreDefinedViews(); 
670        aV3dViewer->NextDefinedViews()) {
671     Handle(V3d_View) aV = aV3dViewer->DefinedView();
672     double aS = aV->Scale();
673     if (aS > aScale) {
674       aScale = aS;
675       aView = aV;
676     }
677   }
678   if (aView.IsNull())
679     return;
680   double aLen = aView->Convert(20);
681
682   SketcherPrs_Tools::setArrowSize(aLen);
683   bool isModified = false;
684   QList<AISObjectPtr> aPrsList = aDisplayer->displayedPresentations();
685   foreach (AISObjectPtr aAIS, aPrsList) {
686     Handle(AIS_InteractiveObject) aAisObj = aAIS->impl<Handle(AIS_InteractiveObject)>();
687
688     Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(aAisObj);
689     if (!aDim.IsNull()) {
690       aDim->DimensionAspect()->ArrowAspect()->SetLength(aLen);
691       aContext->Redisplay(aDim, false);
692       isModified = true;
693     }
694   }
695   if (isModified)
696     aDisplayer->updateViewer();
697 }
698
699
700 void PartSet_Module::customizeObjectBrowser(QWidget* theObjectBrowser)
701 {
702   XGUI_ObjectsBrowser* aOB = dynamic_cast<XGUI_ObjectsBrowser*>(theObjectBrowser);
703   if (aOB) {
704     QLineEdit* aLabel = aOB->activeDocLabel();
705     QPalette aPalet = aLabel->palette();
706     aPalet.setColor(QPalette::Text, QColor(0, 72, 140));
707     aLabel->setPalette(aPalet);
708     aOB->treeView()->setExpandsOnDoubleClick(false);
709     connect(aOB->treeView(), SIGNAL(doubleClicked(const QModelIndex&)), 
710       SLOT(onTreeViewDoubleClick(const QModelIndex&)));
711     connect(aOB, SIGNAL(headerMouseDblClicked(const QModelIndex&)), 
712       SLOT(onTreeViewDoubleClick(const QModelIndex&)));
713     connect(aOB->treeView(), SIGNAL(doubleClicked(const QModelIndex&)), 
714       myDataModel, SLOT(onMouseDoubleClick(const QModelIndex&)));
715   }
716 }
717
718
719 void PartSet_Module::addObjectBrowserMenu(QMenu* theMenu) const
720 {
721   QObjectPtrList aObjects = myWorkshop->selection()->selectedObjects();
722   int aSelected = aObjects.size();
723   SessionPtr aMgr = ModelAPI_Session::get();
724   if (aSelected == 1) {
725     bool hasResult = false;
726     bool hasFeature = false;
727     bool hasParameter = false;
728     ModuleBase_Tools::checkObjects(aObjects, hasResult, hasFeature, hasParameter);
729
730     ObjectPtr aObject = aObjects.first();
731     if (aObject) {
732       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
733       FeaturePtr aPartFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
734       bool isPart = aPart.get() || 
735         (aPartFeature.get() && (aPartFeature->getKind() == PartSetPlugin_Part::ID()));
736       if (isPart) {
737         DocumentPtr aPartDoc;
738         if (!aPart.get()) {
739           aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aPartFeature->firstResult());
740         }
741         if (aPart.get()) // this may be null is Part feature is disabled
742           aPartDoc = aPart->partDoc();
743         if (aMgr->activeDocument() == aPartDoc)
744           theMenu->addAction(myMenuMgr->action("DEACTIVATE_PART_CMD"));
745         else
746           theMenu->addAction(myMenuMgr->action("ACTIVATE_PART_CMD"));
747       } else if (aObject->document() == aMgr->activeDocument()) {
748         if (hasParameter || hasFeature)
749           theMenu->addAction(myMenuMgr->action("EDIT_CMD"));
750       }
751     } else {  // If feature is 0 the it means that selected root object (document)
752       if (aMgr->activeDocument() != aMgr->moduleDocument())
753         theMenu->addAction(myMenuMgr->action("ACTIVATE_PARTSET_CMD"));
754     }
755   } else if (aSelected == 0) {
756     // if there is no selection then it means that upper label is selected
757     QModelIndexList aIndexes = myWorkshop->selection()->selectedIndexes();
758     if (aIndexes.size() == 0) // it means that selection happens in top label outside of tree view
759       if (aMgr->activeDocument() != aMgr->moduleDocument())
760         theMenu->addAction(myMenuMgr->action("ACTIVATE_PARTSET_CMD"));
761   }
762 }
763
764 void PartSet_Module::processEvent(const std::shared_ptr<Events_Message>& theMessage)
765 {
766   if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_DOCUMENT_CHANGED)) {
767     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myWorkshop);
768     XGUI_Workshop* aWorkshop = aConnector->workshop();
769     XGUI_DataTree* aTreeView = aWorkshop->objectBrowser()->treeView();
770     QLineEdit* aLabel = aWorkshop->objectBrowser()->activeDocLabel();
771     QPalette aPalet = aLabel->palette();
772
773     SessionPtr aMgr = ModelAPI_Session::get();
774     DocumentPtr aActiveDoc = aMgr->activeDocument();
775     DocumentPtr aDoc = aMgr->moduleDocument();
776     QModelIndex aOldIndex = myDataModel->activePartTree();
777     if (aActiveDoc == aDoc) {
778       if (aOldIndex.isValid())
779         aTreeView->setExpanded(aOldIndex, false);
780       myDataModel->deactivatePart();
781       aPalet.setColor(QPalette::Text, QColor(0, 72, 140));
782     } else {
783       std::string aGrpName = ModelAPI_ResultPart::group();
784       for (int i = 0; i < aDoc->size(aGrpName); i++) {
785         ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aDoc->object(aGrpName, i));
786         if (aPart->partDoc() == aActiveDoc) {
787           QModelIndex aIndex = myDataModel->partIndex(aPart);
788           if (myDataModel->activatePart(aIndex)) {
789             if (aOldIndex.isValid())
790               aTreeView->setExpanded(aOldIndex, false);
791             aTreeView->setExpanded(myDataModel->activePartTree(), true);
792             aPalet.setColor(QPalette::Text, Qt::black);
793           }
794           break;
795         }
796       }
797     }
798     aLabel->setPalette(aPalet);
799     aWorkshop->updateCommandStatus();
800
801     // Update displayed objects in order to update active color
802     XGUI_Displayer* aDisplayer = aWorkshop->displayer();
803     QObjectPtrList aObjects = aDisplayer->displayedObjects();
804     foreach(ObjectPtr aObj, aObjects)
805       aDisplayer->redisplay(aObj, false);
806     aDisplayer->updateViewer();
807   }
808 }
809
810 void PartSet_Module::onTreeViewDoubleClick(const QModelIndex& theIndex)
811 {
812   SessionPtr aMgr = ModelAPI_Session::get();
813   if (!theIndex.isValid()) {
814     aMgr->setActiveDocument(aMgr->moduleDocument());
815     return;
816   }
817   if (theIndex.column() != 0) // Use only first column
818     return;
819   ObjectPtr aObj = myDataModel->object(theIndex);
820   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
821   if (!aPart.get()) { // Probably this is Feature
822     FeaturePtr aPartFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
823     if (aPartFeature.get() && (aPartFeature->getKind() == PartSetPlugin_Part::ID())) {
824       aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aPartFeature->firstResult());
825     }
826   }
827   if (aPart.get()) { // if this is a part
828     if (aPart->partDoc() == aMgr->activeDocument()) {
829       aMgr->setActiveDocument(aMgr->moduleDocument());
830     } else {
831       aPart->activate();
832     }
833   }
834 }